Javascript Immutable.js:如何通过指定属性值在数组中查找对象
我有一个Immutable.js制作的数组:Javascript Immutable.js:如何通过指定属性值在数组中查找对象,javascript,immutable.js,Javascript,Immutable.js,我有一个Immutable.js制作的数组: var arr = Immutable.List.of( { id: 'id01', enable: true }, { id: 'id02', enable: true }, { id: 'id03', enable:
var arr = Immutable.List.of(
{
id: 'id01',
enable: true
},
{
id: 'id02',
enable: true
},
{
id: 'id03',
enable: true
},
{
id: 'id04',
enable: true
}
);
如何找到id为id03的对象?我想更新它的enable
值,然后获得一个新数组,首先是您需要的,然后是您的列表
const index = arr.findIndex(i => i.id === 'id03')
const newArr = arr.update(index, item => Object.assign({}, item, { enable: false }))
或
我同意@caspg的回答,但是如果您的数组是完全不可变的,那么您也可以编写、使用和: 如果您最终需要更基于切换的解决方案,甚至可以使用。
Array#findIndex
,然后更新对象@foundindex
。。
const newArr = arr.update(
arr.findIndex(i => i.id === 'id03'),
item => Object.assign({}, item, { enable: false })
)
const updatedArr = arr.setIn([
arr.findIndex(e => e.get('id') === 'id03'),
'enable'
], false);