【问题标题】:Immutable.js: How to find an object in an array by specify property valueImmutable.js:如何通过指定属性值在数组中查找对象
【发布时间】:2016-11-15 16:32:26
【问题描述】:

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

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

如何找到id: id03 的对象?我想更新它的enable 值并获得一个新数组

【问题讨论】:

  • Array#findIndex 然后更新对象@找到index..

标签: javascript immutable.js


【解决方案1】:

首先你需要findIndex,然后update你的列表。

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

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

【讨论】:

    【解决方案2】:

    我同意@caspg 的回答,但如果您的数组完全是Immutable,您也可以使用findIndexsetIn 编写:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-03
      • 2016-07-26
      • 2011-07-31
      • 1970-01-01
      • 2013-07-05
      • 2022-08-24
      • 1970-01-01
      相关资源
      最近更新 更多