javascriptecmascript-6ecmascript-2020

How to flat array of object in es6?


I've a array of object like. i want to extract nested object and return it as expected output. My approach is already not working and also not sure its efficient to iterating on large set of data.

const data = [
    {
        name: 'Micheal',
        desc: 'Micheal',
        empObj: {
            empId: 1,
            empName: 'Micheal',
            country: 'UK',
        }
    },
    {
        name: 'Allen',
        desc: 'Allen',
        empObj: {
            empId: 2,
            empName: 'Allen',
            country: 'Germany',

        }
    },
    {
        name: 'Rose',
        desc: 'Rose',
        empObj: {
            empId: 3,
            empName: 'Rose',
            country: 'USA',
        }
    }
];

I need to flat/ convert the data like

[
    {
        name: 'Micheal',
        desc: 'Micheal',
        empId: 1,
        empName: 'Micheal',
        country: 'UK',
    },
    {
        name: 'Allen',
        desc: 'Allen',
        empId: 2,
        empName: 'Allen',
        country: 'Germany',
    },
    
    {
        name: 'Rose',
        desc: 'Rose',    
        empId: 3,
        empName: 'Rose',
        country: 'USA',
    
        
    }
]

but I'm getting

Uncaught TypeError: Cannot convert undefined or null to object

const expected = Object.keys(data.empObj).reduce(function(r, k) {
  return r.concat(k, object.empObj[k]);
}, []);

console.log('expected', expected);

Thanks


Solution

  • You can easily achieve this using map

    data.map(({ name, desc, empObj }) => ({ name, desc, ...empObj }))
    

    const data = [
      {
        name: "Micheal",
        desc: "Micheal",
        empObj: {
          empId: 1,
          empName: "Micheal",
          country: "UK",
        },
      },
      {
        name: "Allen",
        desc: "Allen",
        empObj: {
          empId: 2,
          empName: "Allen",
          country: "Germany",
        },
      },
      {
        name: "Rose",
        desc: "Rose",
        empObj: {
          empId: 3,
          empName: "Rose",
          country: "USA",
        },
      },
    ];
    
    const result = data.map(({ name, desc, empObj }) => ({ name, desc, ...empObj, }));
    
    console.log(result);