如何将嵌套对象数组转换为具有特定键名的非嵌套对象
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'}
]
}]
我需要的输出应该是:
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'}
]
一个简单的flatMap together with the 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);
如何将嵌套对象数组转换为具有特定键名的非嵌套对象:
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'}
]
一个简单的flatMap together with the 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);