How to turn array of objects in unique array?

Viewed 49

This is my initial data:

const data = [
   {
      "user":{
         "amount":"1",
         "date":"2020-07-31T18:34:48.635Z",
         "shiftSelected":"10:00"
      }
   },
   {
      "user":{
         "name":"Name",
         "surname":"aaa",         
         "obs":"eee"
      }
   }
]

I'm trying to turn an array of objects in unique array. This is my output:

const newData = {
  amount: "1",
  date: "2020-07-31T18:34:48.635Z",
  shiftSelected: "10:00",
  name: "Name",
  surname:"aaa",         
  obs:"eee"    
}

I can iterate over the array with a map call: let b = data.map(item => item.user), but I need to write more code to join then. I know that it's possible to do it with one unique logic. I tried but without successful.

3 Answers

You can use reduce with Object.assign to merge the properties of the objects. Note that with this method, later properties will overwrite previous ones.

const data = [
   {
      "user":{
         "amount":"1",
         "date":"2020-07-31T18:34:48.635Z",
         "shiftSelected":"10:00"
      }
   },
   {
      "user":{
         "name":"Name",
         "surname":"aaa",         
         "obs":"eee"
      }
   }
];
const result = data.reduce((acc,{user})=>Object.assign(acc,user), {});
console.log(result);

Object spread syntax will also work.

const data = [
   {
      "user":{
         "amount":"1",
         "date":"2020-07-31T18:34:48.635Z",
         "shiftSelected":"10:00"
      }
   },
   {
      "user":{
         "name":"Name",
         "surname":"aaa",         
         "obs":"eee"
      }
   }
];
const result = data.reduce((acc,{user})=>({...acc, ...user}), {});
console.log(result);

const data = [
   {
      "user":{
         "amount":"1",
         "date":"2020-07-31T18:34:48.635Z",
         "shiftSelected":"10:00"
      }
   },
   {
      "user":{
         "name":"Name",
         "surname":"aaa",         
         "obs":"eee"
      }
   }
]

let b = data.reduce((acc, rec) => {
  const { user } = rec
  return { ...acc, ...user}
}, {} )

console.log(b)

use this after map over datas this is not a logic but.....

const x = data.map(obj => obj.user);

function flatObj(arr) {
  const res = {};
  arr.forEach(y => {
    for(const key in y) {
      res[key] = y[key];
    }
  })
  return res;
}

const resault = flatObj(x);
Related