javascriptreduxspread-syntax

Copy and Update a property of an object in an array


For my app using redux I have an array and I want to update some properties of one object. Because it's redux I need a copy of the array, therefore I want to use the spread operator.

Input:

const original = [{a: "original a", b: "original b"}, {c: "original c", d: "original d"}];

What I tried:

const output = [...o1, Object.assign({}, o1[0], { a: "new value" })];
console.log(o2);

Instead of updating the first object in the array this appends a new object to the array.

//what I want to be the output
[{ a: "updated a", b: "updated b" },{ c: "original c", d: "original d" } ]

Solution

  • You are trying to spread array into an object and adding additional keys for which the output that is coming is correct. If you want the desired output you will have to make the keys same before using spread operator that is if you want override keys of the object at the 0th position you will have to merge to it to an array of the object whose element at 0th position overrides your keys.

    const o1 = [
      { a: "original a", b: "original b" },
      { c: "original c", d: "original d" }
    ];
    
    const updatedObj = [
      {
        a: "updated a",
        b: "updated b"
      }
    ];
    const mergeObj = { ...o1, ...updatedObj };
    const o2 = Object.values(mergeObj);
    console.log(o2);