0

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!

2
  • Your question doesn't appear to have anything to do with JSON at all.. Commented Sep 24, 2017 at 3:02
  • Yeah, you're right. It's just a javascript object. I've already edited the question Commented Sep 24, 2017 at 3:03

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I'd be happy to upvote this answer, but I recommend you explain what's happening here, and formatting code so it isn't all jammed into one line. The person asking the question is clearly new to JavaScript.
or just arr.reduce((accumulator, value) => ({...accumulator, [[value]]: myFunction}), {})
3

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

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.