Search code examples
javascriptecmascript-next

Clone array with spread operator and add inline


With an object I can clone & add like:

   let newObject = {
      ...obj,
      [key]: { 
         ...obj[key],
         thing: true }
   }

So, this adds some objects to an array, then one object's property is updated. I know the item's index to update, but don't want to override existing properties.

Now I want to do the same for array:

   let newArray = [
     ...arr,
     [key]: { 
         ...arr[key],
         thing: true }
   ]

Which might do the same as above.

But that doesn't work.

Should {key}:thing work? I remember reading this somewhere, maybe its ES7?

I could do:

   let newArray = arr.map((item, key) => key === index ? { ...item, thing: true } : item);
 

But I was hoping for a cleaner syntax. I'll accept no if there is no similar syntax.


Solution

  • You can use Object.assign():

    const arr = [{ a: 1 }, { b: 1 }, { c: 1 }];
    const index = 1;
    
    const newArr = Object.assign([], arr, { [index]: { ...arr[index], thing: true } });
    console.log(newArr);