Immutable.js:如何通过指定属性值来查找数组中的对象

hh5*_*188 8 javascript immutable.js

我有一个由Immutable.js制作的数组:

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

我怎样才能找到对象id: id03?我想更新它的enable值并获得一个新的数组

小智 10

首先,您需要findIndex,然后更新您的列表.

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

要么

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


Mik*_*ski 5

我同意@caspg的回答,但是如果您的数组是完全数组Immutable,则还可以使用findIndex和编写setIn

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

甚至使用updateIn,如果您最终需要更多基于切换的解决方案。