我有一個來自資料庫輸入的javascript陣列物件,像這樣:
[{ date: '2021-09-15', type: 'cats', value: 4 },
{ date: '2021-09-15', type: 'dogs', value: 5 },
{ date: '2021-09-16', type: 'cats', value: 1 },
{ date: '2021-09-16', style: 'dogs', value: 4 }]
而我需要這樣的輸出:
[{ date: '2021-09-15', cats: 4, dogs: 5 },
{ 日期: '2021-09-16', cats: 1, dogs: 4 }]
我試圖通過這種方式來使用reduce函式,然而,我無法讓它作業(它正在對資料進行分組,但沒有對其進行修改,因此,它們只剩下一個單一的值)
。const data = [
{ date: '2021-09-15', type: 'cats', value: 4 },
{ date: '2021-09-15', type: 'dogs', value: 5 },
{ date: '2021-09-16', type: 'cats', value: 1 },
{ date: '2021-09-16', style: 'dogs', value: 4 }
]
const groups = data.reduce((groups, item) => /span> {
const key = item[item.date] 。
if (! group[key]) {
groups[item.date] = [] 。
}
if (item.type == "cats" ) {
item.cats = item.value。
} else if (item.type == "dogs") {
item.dogs = item.value。
}
groups[item.date].push(item)。
return組。
}, {});
console.log(group)
.as-console-wrapper { max-height。100% ! important; }
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
uj5u.com熱心網友回復:
如果第二個物件具有相同的date并且已經存在type。這也涵蓋了你有多個具有相同type的物件的情況,那么它將會把value加起來
const arr = [
{ date: "2021-09-15", type: "cats", value: 4 },
{ date: "2021-09-15", style: "cats", value: 5 },
{ date: "2021-09-16", style: "cats", value: 1 },
{ date: "2021-09-16", style: "dogs", value: 4 },
];
const map = new Map();
arr.forEach((o) =>/span> {
const { date, type, value } = o;
if (!map.has(date)) map.set(o.date, { date, [type] : value }) 。
else {
const target = map.get(date)。
const { type: newType, value: newValue } = o;
target[newType] = target[newType] ? target[newType] newValue : newValue;
}
});
const result = [...map.values()]。
console.log(result);
/* This is not a part of answer. 它只是為了給輸出填充高度。所以請忽略它 */
.as-console-wrapper { max-height: 100% ! important; top: 0; }
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
uj5u.com熱心網友回復:
這實際上是一個兩步的程序......
這實際上是一個兩步的程序。
- 收集資料組。
- 收集按
date分組的資料到一個地圖中 。
- 將最終結果轉換為你想要的陣列 。
const data = [{"date": "2021-09-15","type": "cats","value":4}, {"date": "2021-09-15","型別":"狗", "價值": 5},{"date":"2021-09-16", "type": "cats","value": 1},{"date":"2021-09-16", "type": "dogs","value":4}]
const t1 = performance.now()
const mapped = data.reduce((map, { date, type, value }) => /span>{
//獲得日期的當前條目,默認為`{}`。
const obj = map.get(date) ? {}
//合并并設定新條目。
return map.set(date, {
...obj,
[type]: (obj[type] ? ? 0) value
})
}, new Map()
const groups = Array.from(mapped, ([ date, obj ]/span>) => ({
日期。
...obj
}))
const t2 = performance.now()
console.log(group, `)
Took ${t2 - t1}ms`)
.as-console-wrapper { max-height: 100% ! important; }
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
從你的問題中并不清楚,但這個答案總結了同一日期的任何相同型別的值。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/306611.html
標籤:
