我有一个类别数组,里面有项目。我宁愿要一个项目数组,但我也要在项目对象集中分类的一些属性
基本上我想将其展平:
[
{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" }
]
谢谢
答案 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)