1

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)

3 Answers 3

5
menu.map(item => {menuExt[item]=Common.locs[item]});
Sign up to request clarification or add additional context in comments.

2 Comments

Bravo for the newcomer! The one-liner I was looking for, thanks! It works like a charm.
Thanks Hendry for your helpful answer. But please always add an explanation to answers even if it is only a brief one. How to Answer . Otherwise, it gets popped onto the low quality queue and someone like me has to review it :) Kind Regards.
0

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]
    });

Comments

0

The idiomatic way would be to use Array.reduce, because you're taking an array of objects and returning a single object.

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;
}, {});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.