![](/img/trans.png)
[英]Get `val` of property from array of objects inside array of objects based on other property of the object
[英]Create an array of objects based on property from other array of objects
我有一個普通的對象數組,需要根據時間將其轉換為新的指定對象數組。 相似的時間數據應該在同一個object。例如:
我有一組這樣的對象:
[
{
"id": 11,
"roomId": 1,
"startTime": "9",
"name" : "xyz"
},
{
"id": 12,
"roomId": 2,
"startTime": "9",
"name" : "xyz2"
},
{
"id": 13,
"roomId": 3,
"startTime": "10",
"name" : "xyz3"
},
{
"id": 14,
"roomId": 1,
"startTime": "9",
"name" : "xyz4"
}
]
最終結果應該是:
[
{
time: "9",
blocks: {
"1": [{
name: 'xyz'
},
{
name: 'xyz4'
}],
"2": [{
name: 'xyz2'
}]
}
},
{
time: "10",
blocks: {
"3": [{
name: 'xyz3'
}]
}
}
]
Array#reduce
迭代數組,同時更新Map
,其中startTime
是鍵,對應的分組 object 是值Map#values
,按時間獲取分組對象列表 const arr = [ { "id": 11, "roomId": 1, "startTime": "9", "name": "xyz" }, { "id": 12, "roomId": 2, "startTime": "9", "name": "xyz2" }, { "id": 13, "roomId": 3, "startTime": "10", "name": "xyz3" }, { "id": 14, "roomId": 1, "startTime": "9", "name": "xyz4" } ]; const res = [... arr.reduce((map, { id, roomId, startTime, name }) => { const current = map.get(startTime)?? { time: startTime, blocks: {} }; current.blocks[roomId] = [...(current.blocks[roomId]?? []), { name } ]; map.set(startTime, current); return map; }, new Map).values() ]; console.log(res);
您可以將Array.prototype.reduce()與Destructuring assignment相結合, 傳播語法並使用Object.values()獲取結果值
代碼:
const data = [{ id: 11, roomId: 1, startTime: '9', name: 'xyz' },{ id: 12, roomId: 2, startTime: '9', name: 'xyz2' },{ id: 13, roomId: 3, startTime: '10', name: 'xyz3' },{ id: 14, roomId: 1, startTime: '9', name: 'xyz4' }] const dataHash = data.reduce((a, { startTime: st, roomId, name }) => { a[st] = a[st] || { time: st, blocks: {} } a[st].blocks[roomId] = [...(a[st].blocks[roomId] || []), { name }] return a }, {}) const result = Object.values(dataHash) console.log(result)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.