I have an array that looks like this:
const myArray = [
{ 'John': 50 },
{ 'Adam': 29 },
{ 'Jack': 40 }
]
How do I convert the array into an object that looks like this?
const convertedObject = {
'John': 50,
'Adam': 29,
'Jack': 40
}
I have an array that looks like this:
const myArray = [
{ 'John': 50 },
{ 'Adam': 29 },
{ 'Jack': 40 }
]
How do I convert the array into an object that looks like this?
const convertedObject = {
'John': 50,
'Adam': 29,
'Jack': 40
}
You can spread the array into Object.assign()
:
const myArray = [
{ 'John': 50 },
{ 'Adam': 29 },
{ 'Jack': 40 }
]
const convertedObject = Object.assign({}, ...myArray)
console.log(convertedObject)
You can use Array.reduce()
for that:
const myArray = [
{'John':50},
{'Adam':29},
{'Jack':40}
]
var res = myArray.reduce((acc, item) => {
var key = Object.keys(item)[0];
acc[key] = item[key];
return acc;
}, {});
console.log(res);