TransWikia.com

How to turn array of objects in unique array?

Stack Overflow Asked on November 29, 2021

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

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

Answered by M.M.F on November 29, 2021

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)

Answered by AlexAV-dev on November 29, 2021

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

Answered by Unmitigated on November 29, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP