Is there a function where the spread operator changes the value?

let abc = [
  { name: "a" },
  { name: "b"}
];

const editName = (oldName, name, arr) =>
  arr.map(item => {
    if (item.name === oldName) {
      return {
        ...item,
        name
      }
    } else {
      return item;
    }
  });

let updateName = editName("a", "c", abc)
console.log(updateName[0])

I am currently learning to change the value through “map”. However, I don’t know why the value is replaced by the spread operations in the “if” section

dose spread operator have that function?

...item is name: "a", isn’t it?

Answer

Spread operator merges the properties of the objects.

Suppose there are two objects:

let obj1 = {
    name: 'a'
}

let obj2 = {
    name: 'b'
}

Now lets merge their properties using the spread operator,

let finalObj = {}

finalObj = {
    ...obj1,
    ...obj2
}

console.log(finalObj)
// Output: { name: 'b' }

finalObj = {
    ...obj2,
    ...obj1
}

console.log(finalObj)
// Output: { name: 'a' }

If the properties are same, the value gets overridden.

In your case, if you want the spread operator to override the property values in the object, then add it below the key that is to be overridden.

let abc = [
    { name: "a" },
    { name: "b"}
  ];
  
  const editName = (oldName, name, arr) =>
    arr.map(item => {
      if (item.name === oldName) {
        return {
          
          name,
          ...item,
        }
      } else {
        return item;
      }
    });
  
  let updateName = editName("a", "c", abc)
  console.log(updateName[0])