joacoleza joacoleza - 5 months ago 35
Javascript Question

How to create a javascript object with the same attributes as an array?

I'm using this library in my angular 2 application.

The thing is that I want to create the menu dynamically, but I need to use a javascript object. How can I convert an array into the expected object?

Imagine that I have this array:

var arr = ["element1", "element2"];

and I want to convert it to:

element1: myFunction,
element2: myFunction

(myFunction is a function that it's defined in the scope)

Any suggestions? Thanks!

Answer Source

Do something like this

arr.reduce((accumulator, value) => { 
  accumulator[value] = myFunction; 
  return accumulator;
}, {})

Basically what's happening, is that you are using the reduce function to do the same thing as what's happening in the solution with the for-loop.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download