ryy77
ryy77

Reputation: 1294

How to reduce an array of objects into one object with unique properties? JavaScript

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 );
but I get:

{ "undefined": undefined } 

Expected result:

{"a":false,"b":false,"c":true}

Upvotes: 4

Views: 14014

Answers (2)

ByGio1
ByGio1

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

Aniket Raj
Aniket Raj

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

Related Questions