这个问题是关于Immutable.js库的.
我有一个List<T>,哪里T是{name: string, id: number}.我想将其转换为Map<number, T>与id中T的钥匙.使用标准方法toMap给我一个Map顺序索引,并没有办法挂钩.并没有像indexBy或其他方法.怎么做?
Luq*_*aan 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" }
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1402 次 |
| 最近记录: |