Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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}

})
like image 564
Ishmal Ijaz Avatar asked Dec 24 '22 03:12

Ishmal Ijaz


2 Answers

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)
like image 64
Nenad Vracar Avatar answered Mar 06 '23 18:03

Nenad Vracar


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

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

console.log(result);
like image 41
Tarek Essam Avatar answered Mar 06 '23 16:03

Tarek Essam