3

I want to map the java script array into dictionary:

let myArray=['first','second','third'];

Expected Output

result={first:1,second:1,third:1}

Actual Output

result=[{element:1}, {element:1}, {element:1}]

Code:

let myArray=['first','second','third'];

let result=myArray.map(element=>{

    return {element:1}

})
1
  • 1
    return {[element]:1} Commented Oct 14, 2018 at 11:20

4 Answers 4

4

You could do this with Object.assign and spread syntax.

let myArray=['first','second','third'];
let obj = Object.assign({}, ...myArray.map(key => ({[key]: 1})));
console.log(obj)

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

1 Comment

I usually use a reducer for this, but I like this method. Kudos.
2

let myArray=['first','second','third'];

let result = myArray.reduce((agg, ele) => {
   agg[ele] = 1;
   return agg;
}, {});

console.log(result);

3 Comments

My requirement is little bit different @Nenad Vracar answer is right
Sorry for the confusion :)
Not that's not matter. I will appreciate your effort.
2

Why not just a regular for loop?

  const result = {};
  for(const key of myArray)
    result[key] = 1;

3 Comments

+1 for simplicity! (Also, efficiency).
You are right. But my purpose is little bit different. I post the part of the question. I did not post my real problem.
@sunny what? why are you asking a question if you don't need it?
2
   let myArray=['first','second','third'];

   let result=myArray.reduce((obj, element)=>{ 

    return {...obj, [element]:1}
 }, {})

A reducer will incrementally append your new key. The array key syntax uses the value of element as the new key

1 Comment

Fixed it. I'd misunderstood the complete problem.

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.