Reputation: 13987
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?
Upvotes: 3
Views: 2713
Reputation: 15935
Javascript Map https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map now remembers the insertion order. so you can use the Javascript Map.
// you can either create Map from existing object
const myMap = new Map(Object.entries(posts));
// or you can insert one by one,
myMap.set(94,{ title: 'Foo bar', content: 'Blah blah blah...' })
// NOTE: key in map need not be string only
// map can be iterated using forEach
myMap.forEach((value, key) => {
console.log(`${key} = ${value}`);
});
Upvotes: 0
Reputation: 27282
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]]))
Upvotes: 3