gpt4 book ai didi

javascript - Node Js - 展平对象数组

转载 作者:行者123 更新时间:2023-12-02 02:57:22 25 4
gpt4 key购买 nike

我有一个像这样的数组

var data = [
{
family: "Fam A",
category: "Cat A",
products: [
{
name: "Name A1",
style: "Style A1"
},
{
name: "Name A2",
style: "Style A2"
}
]
},
{
family: "Fam B",
category: "Cat B",
products: [
{
name: "Name B1",
style: "Style B1"
},
{
name: "Name B2",
style: "Style B2"
}
]
}
];

我想更改内部对象,如下所示

var data = [
{family:"Fam A", category: "Cat A", name: "Name A1", style:"Style A1"},
{family:"Fam A", category: "Cat A", name: "Name A2", style:"Style A2"},
{family:"Fam B", category: "Cat B", name: "Name B1", style:"Style B1"},
{family:"Fam B", category: "Cat B", name: "Name B2", style:"Style B2"}
]

我尝试使用在其他帖子中找到的 map 和 forEach,但没有任何效果。

var flattened = data.products.map(x => Object.assign(x, { productDetails: data.products }))

function getList(data, arrayKey, arrayName) {
data[arrayKey].forEach(function(element) {
element[arrayName] = data[arrayName];
});
return data[arrayKey];
}

理想的解决方案将能够处理动态的嵌套数量,但不需要继续。

预先感谢您帮助新开发人员!

最佳答案

你可以采取Array#flatMap使用嵌套映射。

var data = [{ family: "Fam A", category: "Cat A", products: [{ name: "Name A1", style: "Style A1" }, { name: "Name A2", style: "Style A2" }] }, { family: "Fam B", category: "Cat B", products: [{ name: "Name B1", style: "Style B1" }, { name: "Name B2", style: "Style B2" }] }],
flat = data.flatMap(({ products, ...o }) => products.map(p => ({ ...o, ...p })));

console.log(flat);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - Node Js - 展平对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60821668/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com