首页 > 解决方案 > 将单个对象数组的数组转换为对象数组

问题描述

我目前有一个数组,如下所示:

const writeable = [
  [{id: 1, name: "item1", write: true}],
  [{id: 3, name: "item3", write: true}]
]

我想将数组数组(所有数组都包含一个对象)转换为对象数组。

我已经尝试通过writeable数组进行映射并将每个项目推入一个新数组,但是因为.map返回一个新数组,所以我得到了相同的结果。有没有办法做到这一点,或者这是不可能的?

预期输出:

const newArray = [
  {id: 1, name: "item1", write: true},
  {id: 3, name: "item3", write: true}
]

标签: javascriptarrays

解决方案


只需使用Array#flat.

const writeable = [
  [{id: 1, name: "item1", write: true}],
  [{id: 3, name: "item3", write: true}]
]
const res = writeable.flat();//default depth is 1
console.log(res);


推荐阅读