![](/img/trans.png)
[英]JavaScript shortest way to map an array of objects to a new array of new objects?
[英]Map array of objects into new groups
我有一個 object 和兩個 arrays 從 API 返回的對象。 我需要嘗試將 map 放入一個新的對象數組中,這樣我就可以對 Vue v-select
組件的數據進行分組。 CodePen 示例
fields: {
current: [
{
name: 'Date'
},
{
name: 'Time'
}
],
previous: [
{
name: 'Birthday'
},
{
name: 'Comments'
}
]
},
我怎樣才能將 map 變成一個看起來像這樣的新對象數組?
grouped: [
{
group: "Current",
},
{
name: "Date"
},
{
name: "Time"
},
{
group: "Previous"
},
{
name: "Birthday"
},
{
name: "Comments"
},
]
使用Object.entries()
獲取組及其值,並使用Array.flatMap()
獲取 map 它們。 創建組的 object,並將其添加到包含組項的數組中。
const flattenGroups = fields => Object.entries(fields).flatMap(([group, items]) => [{ group }, ...items]) const fields = {"current":[{"name":"Date"},{"name":"Time"}],"previous":[{"name":"Birthday"},{"name":"Comments"}]} const result = flattenGroups(fields) console.log(result)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.