Reputation: 1294
How can I reduce an array of objects into one object, with unique properties. I will appreciate any help! Thank you!
const input =
[ { "a": false}
, { "b": false, "c": true }
, { "b": false, "c": true }
, { "a": false }
, { "b": false, "c": true }
, { "b": false, "c": true }
, { "b": false, "c": true, "b": false }
]
// I tried :
const object =
input.reduce( (obj, item) =>
Object.assign(obj, { [item.key]: item.value })
, {});
console.log( object );
{ "undefined": undefined }
Expected result:
{"a":false,"b":false,"c":true}
Upvotes: 4
Views: 14014
Reputation: 121
As you can tell, by using the Array.reduce() method, we can reduce the array to an object by initializing the reducer using an empty object ({}) as the second argument of Array.reduce().
And then in the reducer callback, we can work our way up to build the object using the Object.assign() method like how we initially wanted as an end result.
something like this:
const inputObject = input.reduce(
(previousObject, currentObject) => {
return Object.assign(previousObject, currentObject);
},
{});
console.log(inputObject);
Upvotes: 2
Reputation: 2141
let input = [
{ a: false },
{ b: false, c: true },
{ b: false, c: true },
{ a: false },
{ b: false, c: true },
{ b: false, c: true },
{ b: false, c: true, b: false },
];
let result = input.reduce((prev, curr) => {
Object.assign(prev, curr);
return prev;
}, {});
console.log(result);
Upvotes: 2