慕丝7291255
我会要求您在寻求帮助之前先尝试一下自己,以便以最好的方式从社区获得帮助。您可以尝试使用和.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);
森林海
您可以采用更类似于 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; }