hh54188
hh54188

Reputation: 15626

Immutable.js: How to find an object in an array by specify property value

I have an array made by Immutable.js:

    var arr = Immutable.List.of(
        {
            id: 'id01',
            enable: true
        },
        {
            id: 'id02',
            enable: true
        },
        {
            id: 'id03',
            enable: true
        },
        {
            id: 'id04',
            enable: true
        }
    );

How can I find the object with id: id03? I want to update its enable value and get an new array

Upvotes: 12

Views: 14847

Answers (2)

Mike Aski
Mike Aski

Reputation: 9236

I agree with @caspg's answer, but if your array was completely Immutable, you could also write, using findIndex and setIn:

const updatedArr = arr.setIn([
  arr.findIndex(e => e.get('id') === 'id03'),
  'enable'
], false);

or even use updateIn, if you ultimately need a more toggle-based solution.

Upvotes: 7

caspg
caspg

Reputation: 508

First you need to findIndex, and then update your List.

const index = arr.findIndex(i => i.id === 'id03')
const newArr = arr.update(index, item => Object.assign({}, item, { enable: false }))

OR

const newArr = arr.update(
  arr.findIndex(i => i.id === 'id03'),
  item => Object.assign({}, item, { enable: false }) 
 )

Upvotes: 15

Related Questions