2 回答
TA贡献1859条经验 获得超6个赞
我会要求您在寻求帮助之前先尝试一下自己,以便以最好的方式从社区获得帮助。
您可以尝试使用和.map()解构赋值:find()
const products = [{
id: 5,
productName: "Logitech Mouse",
unitprice: 35
},
{
id: 6,
productName: "Logitech Keyboard",
unitprice: 40
}
];
const cart = [{
id: 101,
userId: 3,
productId: 5,
quantity: 2
},
{
id: 102,
userId: 3,
productId: 6,
quantity: 1
}
];
var res = products.map(({id,...rest}) => {
var cartObj = cart.find(c => c.productId == id);
rest.quantity = (cartObj != undefined && 'quantity' in cartObj) ? cartObj.quantity : 'N/A';
return rest;
});
console.log(res);
TA贡献2011条经验 获得超2个赞
您可以采用更类似于 SQL 的方法为产品创建哈希表,并使用哈希表中对象的所需属性映射购物车,以及quantity
结果,您将获得带有产品名称、单价和数量的新对象。
const
select = (keys, object) => Object.fromEntries(keys.map(k => [k, object[k]])),
products = [{ id: 5, productName: "Logitech Mouse", unitprice: 35 }, { id: 6, productName: "Logitech Keyboard", unitprice: 40 }],
cart = [{ id: 101, userId: 3, productId: 5, quantity: 2 }, { id: 102, userId: 3, productId: 6, quantity: 1 }],
productsMap = products.reduce((r, o) => (r[o.id] = o, r), {}),
result = cart.map(({ productId, quantity }) => ({
...select(['productName', 'unitprice'], productsMap[productId]),
quantity
}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
添加回答
举报