reactjs 从列表创建有序Map

xuo3flqw  于 2022-12-03  发布在  React
关注(0)|答案(2)|浏览(146)

我有一个List

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

还有一个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...' },
};

List实际上保存了Map中项的顺序,因为Map/对象不能保证顺序。

使用上述ListMap创建OrderedMap的最有效方法是什么?

ohfgkhjo

ohfgkhjo1#

在Immutable.js中没有内置的构造函数来处理这个问题,因此您必须自己进行Map:

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

p4rjhz4m2#

JavascriptMaphttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map现在会记住插入顺序,因此您可以使用JavascriptMap。

// 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}`);
});

相关问题