Home > Mobile >  How can I convert nested array of object to non-nested objects with specific key name
How can I convert nested array of object to non-nested objects with specific key name

Time:11-24

How can I convert nested array of object to non-nested objects with specific key name:

data = [{department: 'IT', total: 7, planned: 5, 
    units: [
    {name: 'HR', total: 30, planned: 5, description: 'HR Admin'},
    {name: 'Sales', total: 4, planned: 9, description: 'Sales Admin'}
    ]
    }]

my required output should be:

data = [
{name: 'IT', total: 7, planned: 5, description: ''},
{name: 'HR', total: 30, planned: 5, description: 'HR Admin'},
{name: 'Sales', total: 4, planned: 9, description: 'Sales Admin'}
]

CodePudding user response:

A simple flatMap together with the spread syntax can achieve the desired result.

const data = [
  {
    department: 'IT',
    total: 7,
    planned: 5,
    units: [
      {
        name: 'HR',
        total: 30,
        planned: 5,
        description: 'HR Admin'
      },
      {
        name: 'Sales',
        total: 4,
        planned: 9,
        description: 'Sales Admin'
      }
    ]
  }
];

const result = data.flatMap(( obj ) => {
  return [
    {
      name: obj.department,
      total: obj.total,
      planned: obj.planned,
      description: '',
    },
    ...obj.units,
  ];
});

console.log(result);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related