oscmag
oscmag

Reputation: 31

Update property value in nested array (redux state)

How do you update a certain nested property in redux state?

Let's say I only want to update the "value" property in the object below. I know you shouldn't deep copy the previous state but how do i only change the property of an object in an array in an object of an array?

Thanks in advance!

market {
  shops: [
    {
      name: 'abc',
      items: [
        {
          name: 'item1',
          value: 40,
          id: '234rfds32'
        },
        {}
      ]
    },
    {},
    {}
  ]
}

Something like the following:

state = {
  ...state, 
  shops: [
    ...state.shops,
    shops[index].items = [
      ...shops[index].items,
    ]
  ]
};

Upvotes: 0

Views: 73

Answers (1)

Shanaka Rusith
Shanaka Rusith

Reputation: 431

Something like this would work. (code looks ugly, didn't test though)

var shop =  state.shops[index];
var items = [...shop.items];
items[<index>].value = 'your value';
shop.items = items;
var shops = [...state.shops];
shops[index] = shop;

state = {
...state, 
shops 
};

Upvotes: 1

Related Questions