我正在尝试使用数组创建新对象。我已经使用lodash贴图尝试过。但是我的问题是如何获取特定集合中的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
}
答案 0 :(得分:4)
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
地图功能。
答案 1 :(得分:0)
您可以使用嵌套的reduce函数。
const collect = data => data.reduce((results, item) => {
item.reduce((results, subItem) => {
const current = results.find(i => i.collection === subItem.collection);
if (current) {
current.product_ids.push(subItem.product_id);
} else {
results.push({ collection: subItem.collection, product_ids: [subItem.product_id] });
}
return results;
}, results);
return results;
}, []);
const data = [
[
{
"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"
}
]
];
console.log(collect(data));