-1 javascript arrays object ecmascript-6
如何将对象的嵌套数组转换为具有特定键名称的非嵌套对象:
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'}
]
}]
Run Code Online (Sandbox Code Playgroud)
我所需的输出应该是:
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'}
]
Run Code Online (Sandbox Code Playgroud)
一个简单的flatMap结合扩展语法就可以达到预期的结果。
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);Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
425 次 |
| 最近记录: |