user1526912
user1526912

Reputation: 17210

How to update an object within an array with immutable.js

I wish to update an objects in an array using immutable.js

My object looks like this:

{
    location: '',
    cars: [
      {id: 1, color: blue},
      { id: 2, color: red}
    ]
};

In my code I get for example car id: 2 and change the color { id: 2, color: black}

I now wish to update the car which is at index 1 .

I tried :

const car = { id: 2, color: black}
updateIn([ 'cars'  ], list => list.push(car));

This will only add a new car at the end.

Which function in Immutable JS can I use to update car id # 2.

What’s the correct way to do this with immutable.js

Upvotes: 1

Views: 1786

Answers (2)

Mithril
Mithril

Reputation: 13718

Update element in immutable list by condition:

const data = fromJS({
    location: '',
    cars: [
      {id: 1, color: blue},
      { id: 2, color: red}
    ]
});

const car = { id: 2, color: black}

const index = data.get(['cars']).findIndex(listItem => {
  // condition here
  return listItem.get('id') === car.id;
});

const new_data = data.setIn(['cars', index], car);

Upvotes: 0

erdysson
erdysson

Reputation: 1480

const car = { id: 2, color: black};
const indexToBeUpdated = 1;
updateIn(["cars", indexToBeUpdated], () => car);

whatever the index is, you need to pass it to updateIn methods first argument, which is an array.

Upvotes: 1

Related Questions