![](/img/trans.png)
[英]How to combine all the arrays which are inside another array and delete the last symbol in each word?
[英]Combine All Array Inside of Arrays
我在組合來自另一個數組的數組時遇到問題。
數據
datas = [
{
"id": "22333",
"name": "",
"details": [
{
"value": 1
},
{
"value": 2
}
]
},
{
"id": "4444",
"name": "",
"details": [
{
"value": 99
},
{
"value": 66
}
]
}
]
預期產出
final = [
{
"value": 1
},
{
"value": 2
},
{
"value": 99
},
{
"value": 66
}
]
代碼
datas.map((data) => ({ ...data.details}))
您可以使用flatMap
而不是map
。
flatMap
方法返回一個新數組,該數組通過將給定的回調函數應用於數組的每個元素,然后將結果展平一級而形成。 它與 map() 后跟一個深度為 1 的 flat() 相同,但比分別調用這兩個方法效率稍高。
const datas=[{id:"22333",name:"",details:[{value:1},{value:2}]},{id:"4444",name:"",details:[{value:99},{value:66}]}]; const flattened = datas.flatMap(obj => obj.details); console.log(flattened);
datas.reduce((acc, val) => { return acc.concat(val.details) }, [])
您還可以在此處使用reduce
:
arr.reduce((acc, curr) => {
acc.push(...curr.details);
return acc;
}, [])
const arr = (datas = [ { id: "22333", name: "", details: [ { value: 1, }, { value: 2, }, ], }, { id: "4444", name: "", details: [ { value: 99, }, { value: 66, }, ], }, ]); const result = arr.reduce((acc, curr) => { acc.push(...curr.details); return acc; }, []); console.log(result);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.