Search code examples
javascriptarraysjsonobject

Change array of object value based on another array


const array1 = [
  {
    id: "40",
    alias: "Number",
    name: "Number",
  },
  {
    id: "41",
    alias: "Salary",
    name: "Salary",
  },
];


const array2 = [
  {
    id: "Sum__Salary__U3VtKFVTJTIwRW1wbG95ZWUuU2FsYXJ5KQ__",
    name: "Salary",
  },
  { id: "40", name: "Number" },
];

I want to modify my array2, my 'Salary' id should become "41" in my second array instead of "Sum__Salary__U3VtKFVTJTIwRW1wbG95ZWUuU2FsYXJ5KQ__"

Sharing the snipped which i have tried:

const result = array1
  .filter((array1Value) =>
    [...array2].find(
      (array2Value) => array2Value.name === array1Value.alias
    )
  )
  .map((column) => ({
    id: column.id,
    name: column.name,
  }));
console.log("result: ", result);

The above snippet is working fine, but here I am returning new set of array using map, is there any way where I can replace the values instead of creating new set of array? Looking for good approach to implement this.


Solution

  • Here is the solution using forEach & find high order functions:

    const array1 = [
      {
        id: "40",
        alias: "Number",
        name: "Number",
      },
      {
        id: "41",
        alias: "Salary",
        name: "Salary",
      },
    ];
    
    const array2 = [
      {
        id: "Sum__Salary__U3VtKFVTJTIwRW1wbG95ZWUuU2FsYXJ5KQ__",
        name: "Salary",
      },
      { id: "40", name: "Number" },
    ];
    
    array1.forEach((item1) => {
      const matchingItem = array2.find((item2) => item2.name === item1.alias);
      if (matchingItem) {
        matchingItem.id = item1.id;
      }
    });
    
    console.log("Modified array2:", array2);