如何将以下JavaScript数组转换为由' id'键入的Immutable.Map?列表中的每个对象?
let buttons = [{
id: 'all',
label: 'All',
isSelected: false
}, {
id: '1',
label: '1',
isSelected: true
}, {
id: '2',
label: '2',
isSelected: false
}, {
id: '3',
label: '3',
isSelected: false
}]
我希望能够做到:
map.get('all')
// {id: 'all', label: 'All', isSelected: true}
答案 0 :(得分:1)
这可以通过使用如下所示的不可变JS完成。
var buttons = [{
id: 'all',
label: 'All',
isSelected: false
}, {
id: '1',
label: '1',
isSelected: true
}, {
id: '2',
label: '2',
isSelected: false
}, {
id: '3',
label: '3',
isSelected: false
}];
buttonImmutableList = Immutable.fromJS(buttons)
buttonImmutableMap = buttonImmutableList.reduce((a,c)=> a.set(c.get('id'),c), Immutable.Map())
答案 1 :(得分:0)
使用不可变:
var buttons = [{
id: 'all',
label: 'All',
isSelected: false
}, {
id: '1',
label: '1',
isSelected: true
}, {
id: '2',
label: '2',
isSelected: false
}, {
id: '3',
label: '3',
isSelected: false
}];
var array = {};
for(var index in buttons) {
var token = buttons[index];
array[token.id] = token;
}
var map = new Immutable.Map(array);
var test = map.get('all');
window.alert(test.label);
如果您想添加密钥 - >稍后,将修改映射,从而使当前实例无效。为此,您需要将变量map
重新分配给最新的返回有效实例:
map = map.set(key, value);