简体   繁体   中英

Create a single object from array of objects JavaScript

I have a following data-structure.

[
   {
      NAME: 'TEST_1',
      ORG: 'A',
      FROM: '20191223',
      TO: '99991231'
    },

   {
      NAME: 'TEST_1',
      ORG: 'B',
      FROM: '20191223',
      TO: '99991231'
   },

   {
      NAME: 'TEST_1',
      ORG: 'C',
      FROM: '20191223',
      TO: '99991231'
   }
]

I want to group this array into a single object like this. I am basically grouping the ORG into a single array.

   {
      NAME: 'TEST_1',
      ORG: ['A', 'B', 'C']
      FROM: '20191223',
      TO: '99991231'
   }

You can handle this with reduce higher order function like so :

let arr = [
   {
      NAME: 'TEST_1',
      ORG: 'A',
      FROM: '20191223',
      TO: '99991231'
    },

   {
      NAME: 'TEST_1',
      ORG: 'B',
      FROM: '20191223',
      TO: '99991231'
   },

   {
      NAME: 'TEST_1',
      ORG: 'C',
      FROM: '20191223',
      TO: '99991231'
   }
];

let obj = arr.reduce((prev , curr) => { 

  return {
    ...curr,
    ORG : [...(prev['ORG'] || []) , curr['ORG']
  }
} , {});


console.log(obj)

And the output is just like this :

{ NAME: 'TEST_1',
  ORG: [ 'A', 'B', 'C' ],
  FROM: '20191223',
  TO: '99991231' }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM