Search code examples
arraysjavascript-objectsspread

Cloning object and changing one value


I've got an object:

const data1 = {
    connections: [
      {
        id: 'abfd6e01',
        status: 'active',
        created: '2023-05-10T11:30:25.0000000Z',
      },
    ],
    description: 'Mocked description',
    id: '0e8eabf6',
    name: 'Mocked Company',
  };

What I need to do is to clone the object with status value changed from 'active' to 'passive', like so:

const data1 = {
        connections: [
          {
            id: 'abfd6e01',
            status: 'passive',
            created: '2023-05-10T11:30:25.0000000Z',
          },
        ],
        description: 'Mocked description',
        id: '0e8eabf6',
        name: 'Mocked Company',
      };

My solution is :

const data2 = {...data1, connections:[{...data1.connections, status: 'passive'}]}

Unfortunately what it does is adding '0' key in connections array and additional 'status' key so the result is:

{
  connections: [
      {
          "0": {
              id: "abfd6e01",
              status: "active",
              created: "2023-05-10T11:30:25.0000000Z"
          },
          status: "passive"
      }
  ],
  description: "Mocked description",
  id: "0e8eabf6",
  name: "Mocked Company"
}

Solution

  • You're very close; just change

    ...data1.connections
    

    To:

    ...data1.connections[0]
    

    And you'd be good.

    const data1 = {
        connections: [
          {
            id: 'abfd6e01',
            status: 'active',
            created: '2023-05-10T11:30:25.0000000Z',
          },
        ],
        description: 'Mocked description',
        id: '0e8eabf6',
        name: 'Mocked Company',
      };
    
    const data2 = {...data1, connections:[{...data1.connections[0], status: 'passive'}]};
    
    console.log( data2 );