You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将对象数组转换为数组数组?是否有ES2015便捷方法?

当然可以!ES2015+提供了超简洁的方式搞定这个转换,同时用for循环实现也是完全可行的,我给你分别说明两种方案:

ES2015+ 简洁实现方案

你可以结合Array.prototype.map()和Object.values()这两个ES2015引入的方法,一行代码就能完成转换:

const json = [{one: "text1", two: "text2", three: 3, four: 4}, {one: "text3", two: "text4", three: 5, four: 6}, {one: "text5", two: "text7", three: 8, four: 9}];
const array = json.map(obj => Object.values(obj));

console.log(array);
// 输出结果:[["text1", "text2", 3, 4], ["text3", "text4", 5, 6], ["text5", "text7", 8, 9]]

原理说明

  • map()会遍历原数组的每一个对象元素,对每个元素执行我们传入的回调函数;
  • Object.values()会返回对象自身可枚举属性的值组成的数组,ES2015及之后的规范里,对象的自有属性会按插入顺序排列,所以正好能匹配你需要的顺序。

for循环实现方案

如果需要兼容更旧的环境,或者想要更精细的控制,用for循环完全没问题,甚至可以手动指定属性顺序来避免潜在的顺序问题:

const json = [{one: "text1", two: "text2", three: 3, four: 4}, {one: "text3", two: "text4", three: 5, four: 6}, {one: "text5", two: "text7", three: 8, four: 9}];
const array = [];

for (let i = 0; i < json.length; i++) {
  const currentObj = json[i];
  // 手动按属性顺序提取值,确保顺序完全符合预期
  const itemArray = [currentObj.one, currentObj.two, currentObj.three, currentObj.four];
  array.push(itemArray);
}

console.log(array);
// 同样得到目标数组

这种方式的好处是,哪怕后续对象的属性顺序发生变化(比如新增或调整属性位置),你也能通过手动指定属性来保证子数组的顺序完全符合需求。

内容的提问来源于stack exchange,提问作者Ray

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:30:53