admin管理员组

文章数量:1333414

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 );

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}
Share Improve this question edited Nov 18, 2022 at 19:17 Camilo 7,2145 gold badges45 silver badges66 bronze badges asked Nov 18, 2022 at 15:58 ryy77ryy77 1,2947 gold badges23 silver badges43 bronze badges 6
  • What do you mean by unique properties? – mrconcerned Commented Nov 18, 2022 at 15:59
  • What have you tried so far? – Camilo Commented Nov 18, 2022 at 16:00
  • You can use input.reduce() with proper callback function. You can use Object.assign() as a part of it. – Roman Hocke Commented Nov 18, 2022 at 16:03
  • @Nijat Mursali, i mean "a", "b", "c" to be only once – ryy77 Commented Nov 18, 2022 at 16:09
  • stackoverflow./help/formatting – Mister Jojo Commented Nov 18, 2022 at 16:10
 |  Show 1 more ment

2 Answers 2

Reset to default 2

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);

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);

本文标签: How to reduce an array of objects into one object with unique properties JavaScriptStack Overflow