Reputation: 5717
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
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
Reputation: 138267
Why not just a regular for loop?
const result = {};
for(const key of myArray)
result[key] = 1;
Upvotes: 2
Reputation: 4010
let myArray=['first','second','third'];
let result = myArray.reduce((agg, ele) => {
agg[ele] = 1;
return agg;
}, {});
console.log(result);
Upvotes: 2
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