繁体   English   中英

JavaScript 如何通过两个不同的 arrays 对象并有条件地返回一个数组

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM