如何提取陣列中的陣列并將其構造為一個完整的陣列?
輸入:
const input = [{
categoryName: "Chinese food",
tabs: [{
header: "Chicken Rice",
content: "Hainanese chicken rice is a dish of poached chicken and seasoned rice"
},
{
header: "Dim sum",
content: "large range of small Chinese dishes that are traditionally enjoyed in restaurants"
}
]
},
{
categoryName: "Italian food",
tabs: [{
header: "Pizza",
content: "Dish of Italian origin consisting of a usually round"
}]
},
]
輸出(需要把所有的headers提取出來成為這個陣列)
const output = [
{
"categoryName": "Chinese food",
"header": "Chicken Rice",
},
{
"categoryName": "Chinese food",
"header": "Dim sum",
},
{
"categoryName": "Italian food",
"header": "Pizza"
},
]
uj5u.com熱心網友回復:
以下解決方案實作了以下假設的目標/目標:
標頭始終以相同、統一的方式嵌套。即,它將始終在 tabs prop 陣列中,并且 tabs prop 將始終存在于輸入陣列中的每個物件中。
代碼片段
// extract only 'header', and included 'id'
const getHeadersWithId = arr => (
arr.flatMap( // iterate over 'input' array and 'flat'-ten the result
({tabs}) => (tabs.map( // de-structure 'tabs' & iterate over it
({header}) => ({header}) // de-structure 'header' & retain it to intermediate-result array
))
).map(
({header}, idx) => ({ // iterate with index 'idx'
id: idx 1, // generate the 'id' and store
header // header from intermediate-result array element
})
)
);
const input = [{
categoryName: "Chinese food",
tabs: [{
header: "Chicken Rice",
content: "Hainanese chicken rice is a dish of poached chicken and seasoned rice"
},
{
header: "Dim sum",
content: "large range of small Chinese dishes that are traditionally enjoyed in restaurants"
}
]
},
{
categoryName: "Italian food",
tabs: [{
header: "Pizza",
content: "Dish of Italian origin consisting of a usually round"
}]
},
];
console.log(getHeadersWithId(input));
解釋
添加到上述代碼段的行內注釋。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/455820.html
下一篇:按日期將物件陣列分組為年和月
