12

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

hh54188
  • 14,887
  • 32
  • 113
  • 184

2 Answers2

15

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 }) 
 )
caspg
  • 508
  • 5
  • 8
7

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.

Mike Aski
  • 9,180
  • 4
  • 46
  • 63