gpt4 book ai didi

immutable.js - 不可变JS : Convert List to indexed Map

转载 作者:行者123 更新时间:2023-12-04 10:24:17 25 4
gpt4 key购买 nike

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

我有一个 List<T> ,其中 T{name: string, id: number} .我想把它转换成 Map<number, T> , 与 idT到 key 。使用标准方法 toMap给我一个 Map具有顺序索引,并且无法在那里 Hook 。没有像 indexBy 这样的方法或其他。怎么做?

最佳答案

你可以用这样的 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" }
};

关于immutable.js - 不可变JS : Convert List to indexed Map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33830745/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com