1

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

1
  • Can you add some more code for context? For example, what are you calling updateIn() on? Commented Sep 1, 2016 at 21:24

2 Answers 2

1
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.

Sign up to request clarification or add additional context in comments.

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.