首页 > 解决方案 > 嵌套数组Javascript中的Flattern对象

问题描述

我有一个包含对象的数组数组,想要获取某个键的值并将其作为一个大数组返回,尝试了嵌套映射,但它返回多个数组而不是单个数组。

const items = [
  {
    id: 1,
    sub_items: [
      {
        id: 1
      },
      {
        id: 2
      },
      {
        id: 3
      }
    ]
  },
  {
    id: 2,
    sub_items: [
      {
        id: 4
      },
      {
        id: 5
      },
      {
        id: 6
      }
    ]
  }
]

const subItemIDs = items.map( (item) =>
  item.sub_items.map( (subItem) => subItem.id )
)

console.log(subItemIDs);

预期产出

[1, 2, 3, 4, 5, 6]

实际输出

[ [1,2,3], [4,5,6] ]

标签: javascript

解决方案


您可以使用arrays.flat(). 一旦问题中提到输出,我可以提供更具体的代码

const arr1 = [0, 1, 2, [3, 4]];

console.log(arr1.flat());
// expected output: [0, 1, 2, 3, 4]

const arr2 = [0, 1, 2, [[[3, 4]]]];

console.log(arr2.flat(2));
// expected output: [0, 1, 2, [3, 4]]

推荐阅读