[英]Map through a Javascript array of objects and return a new one satisfying a condition
[英]JavaScript how to map through two different arrays of objects and return one array conditionally
您好,我需要幫助在以下示例數組中動態創建 newProducts,而不知道其他兩個 arrays https://jsfiddle.net/od4267fv/中的內容:
我想檢查
products = [
{
id: 1,
name: 'product 1' ,
liked: false
},
{
id: 2,
name: 'product 2' ,
liked: false
},
{
id: 3,
name: 'product 3' ,
liked: false
},
{
id: 4,
name: 'product 4' ,
liked: false
},
{
id: 5,
name: 'product 5' ,
liked: false
},
]
likedProducts = [
{
id: 1,
name: 'product 1' ,
liked: true
},
{
id: 2,
name: 'product 2' ,
liked: true
},
{
id: 3,
name: 'product 3' ,
liked: true
},
]
if proucts[product].id === likedProducts[product].id
newProducts.push(likedProducts[product])
else
newProducts.push(proucts[product])
請推薦合適的方法
嘗試這個
const allProducts = products.filter(n => likedProducts.find(n2 => n.id == n2.id));
您可以使用map()和findIndex()執行以下操作,
products = [ { id: 1, name: 'product 1', liked: false }, { id: 2, name: 'product 2', liked: false }, { id: 3, name: 'product 3', liked: false }, { id: 4, name: 'product 4', liked: false }, { id: 5, name: 'product 5', liked: false }, ] likedProducts = [ { id: 1, name: 'product 1', liked: true }, { id: 2, name: 'product 2', liked: true }, { id: 3, name: 'product 3', liked: true }, ] newProducts = products.map(item => { let index = likedProducts.findIndex(likedProduct => likedProduct.id === item.id); if(index > -1) { return likedProducts[index]; } return item; }) console.log(newProducts);
這是在某些特定條件下迭代 2 個數組並更新值的方法。
const updatedProduct = proucts.map((row, indexOfRows) => { for (let index = 0; index < likedProducts.length; index++) { if (likedProducts[index].id === row.id) { return likedProducts[index]; } } return row; });
您可以對每個 arrays 進行一次迭代。 首先按 id 索引所有產品,然后遍歷喜歡的產品並覆蓋索引的項目。 這樣,每個數組有多少項都沒有關系,也不需要對至少一個 arrays 進行持續查找。
const products = [{id: 1,name: 'product 1',liked: false},{id: 2,name: 'product 2',liked: false},{id: 3,name: 'product 3',liked: false},{id: 4,name: 'product 4',liked: false},{id: 5,name: 'product 5',liked: false},]; const likedProducts = [{id: 1,name: 'product 1',liked: true},{id: 2,name: 'product 2',liked: true},{id: 3,name: 'product 3',liked: true},]; const index = new Map(); //index all products for (let item of products) { index.set(item.id, item); } //overwrite anything that is liked for (let likedItem of likedProducts) { if (index.has(likedItem.id)) { index.set(likedItem.id, likedItem); } } //construct a new array from the values const result = Array.from(index.values()); console.log(result);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.