展平数组的对象

时间:2019-05-18 17:37:15

标签: javascript

我有一个类别数组,里面有项目。我宁愿要一个项目数组,但我也要在项目对象集中分类的一些属性

基本上我想将其展平:

[
 {catname: "caregory1", items: [{ name: "item1" }, {name: "item2"}] }
 {catname: "caregory2", items: [{ name: "item3" }, {name: "item4"}, {name: "item5"}] }
]

进入这个?

[
 {catname: "caregory1", name: "item1" }
 {catname: "caregory1", name: "item2" }
 {catname: "caregory2", name: "item3" },
 {catname: "caregory2", name: "item4" },
 {catname: "caregory2", name: "item5" }
]

谢谢

1 个答案:

答案 0 :(得分:0)

您可以为此使用flatMap()map()

  • 在主数组上使用flatMap(),并通过对象解构和散布的stynax隔离items属性和其余属性
  • 然后在数组的map()属性上使用items并返回具有父项items以外的属性的嵌套对象的属性。

const arr = [
 {catname: "caregory1", items: [{ name: "item1" }, {name: "item2"}] },
 {catname: "caregory2", items: [{ name: "item3" }, {name: "item4"}, {name: "item5"}] }
]

const res = arr.flatMap(({items,...rest}) => items.map(a => ({...a,...rest})))

console.log(res)

如果您使用的浏览器不支持flatMap(),请使用concat()

const arr = [
 {catname: "caregory1", items: [{ name: "item1" }, {name: "item2"}] },
 {catname: "caregory2", items: [{ name: "item3" }, {name: "item4"}, {name: "item5"}] }
]

const res = [].concat(...arr.map(({items,...rest}) => items.map(a => ({...a,...rest}))))

console.log(res)