我正在尝试用数组创建新对象。我已经使用 lodash map 进行了尝试。但我的问题是如何获取特定集合中的 product_ids 并将其放入数组中。
这是对象
[
[
{
"id": "b7079be6-c9ab-4d24-9a1d-38eddde926c2",
"collection": "mortgages",
"product_id": "854174665132787596022"
},
{
"id": "0da12779-6fe9-45d5-afbf-91d2466e5b7e",
"collection": "mortgages",
"product_id": "304285269353822734222"
},
{
"id": "87a137ba-5f66-4e94-8d5d-698dfbaa08ec",
"collection": "mortgages",
"product_id": "-304414504724243127922"
}
],
[
{
"id": "522f4b83-4c5a-4ffe-836d-33a51325d251",
"collection": "carinsurance",
"product_id": "10413803"
},
{
"id": "02b79566-9cf7-48fa-a8d3-eecf951b5a76",
"collection": "carinsurance",
"product_id": "10397803"
}
]
]
我已经试过这段代码了
map(this.products, (item, key) => {
this.arr.push({
collection: item[0].collection,
product_ids: item.product_id
});
});
我想要这样的结果。
{
"collection": "mortgages",
"product_ids": [
"304285269353822734222",
"854174665132787596022",
"-304414504724243127922"
]
},
{
"collection": "carinsurance",
"product_ids": [
"10413803",
"10397803"
]
}
但我得到了这个结果。谁能帮我解决这个问题。
{
"collection": "mortgages",
"product_ids": undefined
},
{
"collection": "carinsurance",
"product_ids": undefined
}
最佳答案
item
在你的情况下是一个数组,但你正在访问它,就好像有一个 product_id
数组本身的字段,你必须映射所有 product_id
数组中每个项目的属性:
map(this.products, (item, key) => {
return {
collection: item[0].collection,
product_ids: item.map(i => i.product_id)
};
});
此外,如果 map 函数返回一个数组,对于初始数组中的每个项目,它会将其转换为新格式,因此您可以返回并分配给 this.arr
而不是推送到 this.arr
在 map 函数中。
关于javascript - 迭代对象数组以合并新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57386513/