Immutable.js: 如何通过指定 属性 值在数组中查找对象
Immutable.js: How to find an object in an array by specify property value
我有一个数组 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
值并得到一个新数组
首先你需要findIndex, and then 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 })
)
我同意@caspg的回答,但是如果你的数组完全是Immutable
,你也可以写,使用findIndex
and setIn
:
const updatedArr = arr.setIn([
arr.findIndex(e => e.get('id') === 'id03'),
'enable'
], false);
甚至使用 updateIn
,如果您最终需要一个更基于切换的解决方案。
我有一个数组 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
值并得到一个新数组
首先你需要findIndex, and then 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 })
)
我同意@caspg的回答,但是如果你的数组完全是Immutable
,你也可以写,使用findIndex
and setIn
:
const updatedArr = arr.setIn([
arr.findIndex(e => e.get('id') === 'id03'),
'enable'
], false);
甚至使用 updateIn
,如果您最终需要一个更基于切换的解决方案。