【问题标题】:How can I convert nested array of object to non-nested objects with specific key name如何将嵌套的对象数组转换为具有特定键名的非嵌套对象
【发布时间】:2022-01-02 14:56:12
【问题描述】:

如何将嵌套的对象数组转换为具有特定键名的非嵌套对象:

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'}
    ]
    }]

我需要的输出应该是:

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'}
]

【问题讨论】:

标签: javascript arrays object ecmascript-6


【解决方案1】:

一个简单的flatMap 加上spread syntax 就可以达到预期的效果。

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

【讨论】:

  • 很好,但也许不要沉迷于糟糕的问题
  • 抱歉,现在知道flatMap方法了,谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-09-23
  • 1970-01-01
  • 2021-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多