以下代碼產生了所需的結果,但有沒有辦法重構它以消除accumulator變數?
const data = [
{ id: "428", date: "2017-01-24" },
{ id: "526", date: "2022-01-01" },
{ id: "428", name: "George" },
{ id: "526", name: "Sam" },
{ id: "827", name: "Dan" }
];
const accumulator = {};
data.forEach(o => {
accumulator[o.id] = { ...accumulator[o.id] , ...o } || o;
});
console.log(accumulator);
uj5u.com熱心網友回復:
內置方法reduce已經這樣做了。將累加器作為第二個引數傳遞。回呼中的第一個引數是累積值。第二個是本次迭代中的當前物件。回呼的回傳值作為累加值傳遞給下一次迭代。
const data = [
{ id: "428", date: "2017-01-24" },
{ id: "526", date: "2022-01-01" },
{ id: "428", name: "George" },
{ id: "526", name: "Sam" },
{ id: "827", name: "Dan" },
];
const result = data.reduce((accumulator, o) => {
accumulator[o.id] = { ...accumulator[o.id] , ...o } || o;
return accumulator;
}, {});
console.log(result);
uj5u.com熱心網友回復:
|| o部分沒有意義(物件總是真實的),重復傳播可能成為嚴重的性能陷阱。Object.create(null)當使用物件作為地圖時,避免鍵與上面的東西發生沖突也是一種很好的做法Object.prototype(即使目前看起來你有數字鍵)。
那么,讓我們從這個更高效、更可靠的版本重新開始:
const accumulator = Object.create(null);
data.forEach(o => {
Object.assign(accumulator[o.id] ??= {}, o);
});
考慮到這一點,Object.assign已經回傳正在更新的物件,因此使用起來很方便Array.prototype.reduce:
const accumulator = data.reduce(
(accumulator, o) => Object.assign(accumulator[o.id] ??= {}, o),
Object.create(null)
);
uj5u.com熱心網友回復:
您可以使用 減少資料集Array.prototype.reduce。只需通過id累加器 ( acc) 中的鍵找到前一個物件或使用一個新物件,然后將當前物件分布在它上面。
const data = [
{ id: "428", date: "2017-01-24" },
{ id: "526", date: "2022-01-01" },
{ id: "428", name: "George" },
{ id: "526", name: "Sam" },
{ id: "827", name: "Dan" }
];
const reducedData = data.reduce((acc, obj) =>
({ ...acc, [obj.id]: {...(acc[obj.id] ?? {}), ...obj } }), {});
console.log(reducedData);
.as-console-wrapper { top: 0; max-height: 100% !important; }
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/480368.html
標籤:javascript
