Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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}
like image 604
ryy77 Avatar asked Sep 05 '25 01:09

ryy77


2 Answers

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);
like image 151
Aniket Raj Avatar answered Sep 07 '25 09:09

Aniket Raj


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);
like image 45
ByGio1 Avatar answered Sep 07 '25 07:09

ByGio1