【问题标题】:How to add property value from one array of objects into another (for the matching objects) in JS如何在JS中将一个对象数组中的属性值添加到另一个对象(对于匹配的对象)
【发布时间】:2021-03-24 10:52:11
【问题描述】:

我正在尝试根据另一个对象数组过滤对象数组,在找到所有匹配项后,我想将第一个数组对象中的属性和值设置为第二个数组中的相应对象:

 const searchedProducts = products.filter(product =>
        uniqueProducts.some(
          uniqueProduct =>
            product.productId === uniqueProduct.productId,
        ),
      )

在此之后,我需要为 productName 属性下的每个唯一产品对象设置 product.productName。

何以更好的方式实现这样的事情?

【问题讨论】:

  • 请提供示例输入和预期输出。
  • @pilchard 我只需要更新 uniqueProducts 新属性 productName 将可用并从 products 对象数组设置
  • 以后我建议提供minimal reproducible example,这样回答就不是猜测工作或额外工作了。

标签: javascript arrays ecmascript-6 javascript-objects ecmascript-5


【解决方案1】:

这可能是最直接的使用reduce() 结合find() 来检索和验证第二个数组是否包含每个对象。

const uniqueProducts = [
  {id: 3, from: 'uniqueProducts', name: 'Unique 1'},
  {id: 12, from: 'uniqueProducts', name: 'Unique 12'}
];

const products = [
  {id: 1, from: 'products',  name: 'Product 1'},
  {id: 2, from: 'products', name: 'Product 2'},
  {id: 9, from: 'products', name: 'Product 9'},
  {id: 12, from: 'products', name: 'Product 12'},
];

const output = products.reduce((a, p) => {
  const uP = uniqueProducts.find(u => u.id === p.id);
  if (uP) a.push({...p, name: uP.name});
  return a;
}, []);

console.log(output);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-09-23
    • 1970-01-01
    • 1970-01-01
    • 2021-12-28
    • 2022-11-21
    • 2019-04-11
    • 2020-04-09
    • 1970-01-01
    相关资源
    最近更新 更多