通过自定义键将 Seq 转换为 Map

Convert Seq to Map by custom key

如何将以下 JavaScript 数组转换为由列表中每个对象的 'id' 键控的 Immutable.Map?

    id: 'all',
    label: 'All',
    isSelected: false
  }, {
    id: '1',
    label: '1',
    isSelected: true
  }, {
    id: '2',
    label: '2',
    isSelected: false
  }, {
    id: '3',
    label: '3',
    isSelected: false
}]

我希望能够做到:

// {id: 'all', label: 'All', isSelected: true}

使用不可变:

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);

这可以通过使用不可变的 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())