ImmutableJS:将List转换为索引Map

时间:2015-11-20 15:48:37

标签: immutable.js

这个问题是关于Immutable.js库。

我有一个List<T>,其中T{name: string, id: number}。我想将其转换为Map<number, T> id T的密钥。使用标准方法toMap给我一个带有顺序索引的Map,并且没有办法挂钩。没有像indexBy或其他方法那样的方法。怎么做?

1 个答案:

答案 0 :(得分:13)

你可以使用这样的reducer:

function indexBy(iterable, searchKey) {
    return iterable.reduce(
        (lookup, item) => lookup.set(item.get(searchKey), item),
        Immutable.Map()
    );
}

var things = Immutable.fromJS([
    {id: 'id-1', lol: 'abc'},
    {id: 'id-2', lol: 'def'},
    {id: 'id-3', lol: 'jkl'}
]);
var thingsLookup = indexBy(things, 'id');
thingsLookup.toJS() === {
  "id-1": { "id": "id-1", "lol": "abc" },
  "id-2": { "id": "id-2", "lol": "def" },
  "id-3": { "id": "id-3", "lol": "jkl" }
};
相关问题