使用 JavaScript 對所有擁有相同 '_id' 鍵值的具象集合進行分組
假設我們有一個類似如下這樣的物件陣列 −
const arr = [ {_id : "1", S : "2"}, {_id : "1", M : "4"}, {_id : "2", M : "1"}, {_id : "" , M : "1"}, {_id : "3", S : "3"} ];
我們需要編寫一個 JavaScript 函式,其能夠獲取這樣的陣列,並將具有相同 '_id' 鍵值的具象分組到一起。
因此,最終的輸出應類似如下 −
const output = [ {_id : "1", M : "4", S : "2", Total: "6"}, {_id : "2", M : "1", S : "0", Total: "1"}, {_id : "6", M : "1", S : "0", Total: "1"}, {_id : "3", M : "0", S : "3", Total: "3"} ];
示例
程式碼如下 −
const arr = [ {_id : "1", S : "2"}, {_id : "1", M : "4"}, {_id : "2", M : "1"}, {_id : "6" , M : "1"}, {_id : "3", S : "3"} ]; const pickAllConstraints = arr => { let constraints = []; arr.forEach(el => { const keys = Object.keys(el); constraints = [...constraints, ...keys]; }); return constraints.filter((el, ind) => el !== '_id' && ind === constraints.lastIndexOf(el)); }; const buildItem = (cons, el = {}, prev = {}) => { const item = {}; let total = 0 cons.forEach(i => { item[i] = (+el[i] || 0) + (+prev[i] || 0); total += item[i]; }); item.total = total; return item; } const buildCumulativeArray = arr => { const constraints = pickAllConstraints(arr); const map = {}, res = []; arr.forEach(el => { const { _id } = el; if(map.hasOwnProperty(_id)){ res[map[_id] - 1] = { _id, ...buildItem(constraints, el, res[map[_id] - 1]) }; }else{ map[_id] = res.push({ _id, ...buildItem(constraints, el) }); } }); return res; }; console.log(buildCumulativeArray(arr));
輸出
控制檯中的輸出如下 −
[ { _id: '1', M: 4, S: 2, total: 6 }, { _id: '2', M: 1, S: 0, total: 1 }, { _id: '6', M: 1, S: 0, total: 1 }, { _id: '3', M: 0, S: 3, total: 3 } ]
廣告