Reputation: 7935
I am struggling to find a way to combine an array of objects into one object. All the solutions I have come across so far yield an array as the result, but I need an object. Here is an example:
[
{
'1112225544': '1',
'3258458756': '9',
'3654125412': '5',
},
{
'2229993827': '0',
'9827719902': '1',
'0000000000': '2',
'1112225544': '3',
},
...
]
There can be many objects inside the array. I want to flatten them and get this as the output:
{
'3258458756': '9',
'3654125412': '5',
'2229993827': '0',
'9827719902': '1',
'0000000000': '2',
'1112225544': '3'
}
Notice that the duplicate keys get overridden by whatever values the last array has. The solutions I have seen thus far are of this variety and don't quite work for me.
Upvotes: 2
Views: 136
Reputation: 7555
This is achievable with a single command. Use Object.assign
and spread the array in.
Object.assign({}, ...[
{
'1112225544': '1',
'3258458756': '9',
'3654125412': '5',
},
{
'2229993827': '0',
'9827719902': '1',
'0000000000': '2',
'1112225544': '3',
},
])
Upvotes: 2
Reputation: 458
Or old way:
let items = [
{
'1112225544': '1',
'3258458756': '9',
'3654125412': '5',
},
{
'2229993827': '0',
'9827719902': '1',
'0000000000': '2',
'1112225544': '3',
},
];
let result = {};
for (let item of items)
result = Object.assign(result, item)
console.log(result)
Upvotes: 1
Reputation: 4227
let arr = [{1112225544:"1",3258458756:"9",3654125412:"5"},{2229993827:"0",9827719902:"1","0000000000":"2",1112225544:"3"}];
let result = Object.fromEntries(arr.flatMap(e => Object.entries(e)))
console.log(result)
Upvotes: 0
Reputation: 22431
this way ?
const arr1 =
[ { '1112225544': '1'
, '3258458756': '9'
, '3654125412': '5'
}
, { '2229993827': '0'
, '9827719902': '1'
, '0000000000': '2'
, '1112225544': '3'
}
//...
]
const arr2 = arr1.reduce((r,c)=>
{
Object.entries(c).forEach(([k,v]) => r[k] = v )
return r
},{})
console.log( arr2 )
.as-console-wrapper { max-height: 100% !important; top: 0 }
Upvotes: 1
Reputation: 25453
Here's an approach using Array.prototype.reduce:
[
{
'1112225544': '1',
'3258458756': '9',
'3654125412': '5',
},
{
'2229993827': '0',
'9827719902': '1',
'0000000000': '2',
'1112225544': '3',
},
].reduce(
(acc, curr) => ({
...curr,
...acc,
}),
{}
);
Whenever I have a need to "reduce" an array into either a scaler or object type, reduce
is usually considered.
Upvotes: 4
Reputation: 28685
let data = [
{
'1112225544': '1',
'3258458756': '9',
'3654125412': '5',
},
{
'2229993827': '0',
'9827719902': '1',
'0000000000': '2',
'1112225544': '3',
},
];
let result = {};
data.forEach(x=>{
Object.entries(x).forEach(([k,v])=>result[k]=v)
})
console.log(result)
Or
let data = [
{
'1112225544': '1',
'3258458756': '9',
'3654125412': '5',
},
{
'2229993827': '0',
'9827719902': '1',
'0000000000': '2',
'1112225544': '3',
},
];
let result = {};
data.forEach(x=>{
result = {...result, ...x}
})
console.log(result)
Upvotes: 5