javascriptreactjsfunctional-programmingreduximmutable.js

Immutable JS - Creating an OrderedMap from a List


I have a List

const results = [94, 88, 121, 17];

and also a Map

const posts = {
   94: { title: 'Foo bar', content: 'Blah blah blah...' },
   88: { title: 'Bar Foo', content: 'Blah blah blah...' },
   121: { title: 'Bing bang', content: 'Blah blah blah...' },
   17: { title: 'Ning nang', content: 'Blah blah blah...' },
};

The List actually holds the order of the items in the Map as maps/objects can not guarantee order.

Whats the most efficient way to create an OrderedMap using both the List and the Map above?


Solution

  • There's no built-in constructor in Immutable.js that will handle this, so you'll have to do the mapping yourself:

    const orderedPosts = new OrderedMap(results.map(key => [key, posts[key]]))