Ishmal Ijaz
Ishmal Ijaz

Reputation: 5717

JavaScript Array into Dictionary mapping not working properly?

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}

})

Upvotes: 4

Views: 77

Answers (4)

Mild Fuzz
Mild Fuzz

Reputation: 30671

   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

Upvotes: 2

Jonas Wilms
Jonas Wilms

Reputation: 138267

Why not just a regular for loop?

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

Upvotes: 2

Tarek Essam
Tarek Essam

Reputation: 4010

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

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

console.log(result);

Upvotes: 2

Nenad Vracar
Nenad Vracar

Reputation: 122047

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)

Upvotes: 4

Related Questions