Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace values of an array of objects from another array of objects in JavaScript

So I have this main array:

 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
  },

And I'd like to replace the localized_title with an array that contains some updated localized_title for certain product_ids

example:

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

In this case, the purchaseData's first child only should have its localized_title updated. Is there an elegant way of doing this without using For...lopps and without mutating the data? I've tried many ways but I seem to write too many lines of code (not very clean).

This is what I tried:

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;
  });
like image 345
Bassem Avatar asked Aug 31 '25 03:08

Bassem


2 Answers

I'd use a Map to simplify retrieving the objects(this also makes the code 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;
 });
like image 110
Jonas Wilms Avatar answered Sep 02 '25 17:09

Jonas Wilms


It will be worth it to optimize your lookup using a Map to reduce the search for foundObject from O(n) to O(1), and instead of having two return statements, you could combine them into one:

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;
});
like image 43
Patrick Roberts Avatar answered Sep 02 '25 17:09

Patrick Roberts