从JavaScript中的另一个对象数组替换一个对象数组的值

时间:2020-01-21 21:00:20

标签: javascript arrays object

所以我有这个主数组:

 const purchaseData = [
  {
    product_id: "product_id_1",
    localized_title: "Product Title 1",
    ... other attributes
  },
  {
    product_id: "product_id_2",
    localized_title: "Product Title 2",
    ... other attributes
  },

我想用一个包含某些product_id的更新的localized_title的数组替换localized_title

示例:

updatedData = [
  {
    product_id: "product_id_1",
    localized_title: "Updated Product Title 1",
    ...other random attributes // different from the attributes in the objects of purchaseData
  },
];

在这种情况下,purchaseData的第一个孩子应该只更新其localized_title。是否有一种不使用For ... lopps且不变异数据的优雅方法?我已经尝试了很多方法,但是似乎写了很多行代码(不是很干净)。

这是我尝试过的:

const updatedData = purchaseData.map(obj => {
    const foundObject = originalProducts.find(
      o => o.product_id === obj.product_id,
    );
    const localized_title = foundObject && foundObject.localized_title
    if (localized_title) {
        return {...obj, localized_title}
    }
    return obj;
  });

2 个答案:

答案 0 :(得分:3)

我将使用Map简化对象的检索(这也使代码O(n)):

  const productById = new Map(products.map(it => ([it.product_id, it])));

  const updated = purchases.map(purchase => {
    const product = productById.get(purchase.product_id);

    if (product && product.localized_title) {
      return { ...purchase, localized_title: product.localized_title, };
    }

    return purchase;
 });

答案 1 :(得分:1)

使用Map优化查找以将对foundObject的搜索从O(n)减少到O(1)而不是使用两个return来进行优化是值得的语句,您可以将它们组合为一个:

const originalProductsMap = new Map(
  originalProducts.map(o => [o.product_id, o])
);

const updatedData = purchaseData.map(oldData => {
  const newData = originalProductsMap.get(oldData.product_id);
  const localized_title = newData && newData.localized_title;

  return localized_title
    ? { ...oldData, localized_title }
    : oldData;
});