如何將物件的嵌套陣列轉換為具有特定鍵名的非嵌套物件:
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'}
]
uj5u.com熱心網友回復:
一個簡單的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);
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/364762.html
標籤:javascript 数组 目的 ecmascript-6
上一篇:如何授予DDB匯出服務訪問不同AWS賬戶中的存盤桶的權限?
下一篇:獲取影像作為物件
