Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ImmutableJS: Convert List to indexed Map

Tags:

immutable.js

This question is about Immutable.js library.

I have a List<T>, where T is {name: string, id: number}. I want to convert it to Map<number, T>, with id of T to the keys. Using standard method toMap gives me a Map with sequential indexes, and there is no way to hook there. And no method like indexBy or other. how to do that?

like image 922
Artur Eshenbrener Avatar asked Nov 20 '15 15:11

Artur Eshenbrener


1 Answers

You can do it with a reducer like this:

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" }
};
like image 113
Luqmaan Avatar answered Nov 09 '22 22:11

Luqmaan