Reputation: 825
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!
Upvotes: 0
Views: 43
Reputation: 660
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.
Upvotes: 3
Reputation: 5546
Use forEach function on array and create key value pair.
var arr = ["element1", "element2"];
var obj = {};
arr.forEach(function(item){
obj[item]= function myfunction(){};
});
console.log(obj);
Upvotes: 3