Reputation: 3885
I have an array like
let arr = [
{ key: "Text1", value: "Line 1" },
{ key: "Text2", value: "Line 2" },
{ key: "Text3", value: "Line 3" }
]
and I want to turn it into
let obj = {
"Text1": "Line1",
"Text2": "Line2",
"Text3": "Line3"
}
in es6 i was trying something like this but that's definitely wrong. Any help please?
let temp = Object.assign({}, ...arr.map( {key, value} => ( {key, value} ) ));
Upvotes: 2
Views: 97
Reputation: 1
You can do this with .reduce
let arr = [{ key: "Text1", value: "Line 1" }, { key: "Text2", value: "Line 2" }, { key: "Text3", value: "Line 3" }],
result = arr.reduce((r,k)=>(r[k.key]=k.value,r),{});
console.log(result);
Upvotes: 0
Reputation: 386600
You could use Object.assign
and a destructuring and a spread syntex for the items of the mapped objects.
Basically you need more parenthesis around the arguments and a computed key.
Object.assign({}, ...arr.map(({ key, value }) => ({ [key]: value })));
// ^ ^ parenthesis
// ^ ^ computed property
let arr = [{ key: "Text1", value: "Line 1" }, { key: "Text2", value: "Line 2" }, { key: "Text3", value: "Line 3" }],
result = Object.assign({}, ...arr.map(({ key, value }) => ({ [key]: value })));
console.log(result);
Upvotes: 3
Reputation: 3268
You could solve this with reduce:
arr.reduce((o, el) => {
o[el.key] = el.value;
return o;
}, {});
returns
{Text1: "Line 1", Text2: "Line 2", Text3: "Line 3"}
Upvotes: 3
Reputation: 2061
You can do it like this
let arr = [
{ key: "Text1", value: "Line 1" },
{ key: "Text2", value: "Line 2" },
{ key: "Text3", value: "Line 3" }
]
var obj ={};
arr.forEach(function(value){
obj[value.key]=value.value;
})
console.log(obj)
Upvotes: 2