[英]Map an array to an object, using array values as keys
I have我有
const menu = ['home', 'news', 'about'];
I want to map it to this:我想把它映射到这个:
let menuExt =
{
home: Common.locs['home'],
news: Common.locs['news'],
about: Common.locs['about']
};
How do I do that ?我该怎么做? I tried
我试过
let menuExt = menu.map(item => {
return {
item: Common.locs[item]
}
});
but I got an array with "item" as property, but I want one object with properties home, news, about... (there are many more but I shortened it here)但是我得到了一个带有“item”作为属性的数组,但是我想要一个带有属性 home、news、about 的对象(还有更多,但我在这里缩短了它)
menu.map(item => {menuExt[item]=Common.locs[item]});
I managed this way, but I don't know if there is a cleaner and faster solution maybe:我是这样管理的,但我不知道是否有更清洁、更快的解决方案:
let menuExt = {}
menu.forEach((item) => {
menuExt[item] = Common.locs[item]
});
The idiomatic way would be to use Array.reduce
, because you're taking an array of objects and returning a single object.惯用的方法是使用
Array.reduce
,因为您正在获取一组对象并返回一个对象。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
const menu = ['home', 'news', 'about'];
const menuExt = menu.reduce((acc, key) => {
acc[key] = Common.locs[key];
return acc;
}, {});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.