我需要使用計數將常見物件分組為單個,如何根據物件中的 id 對物件進行分組以及如何在結果中添加帶有計數的額外鍵。
var a =[
{"name":"test","id":101,"price":100},
{"name":"test","id":101,"price":100},
{"name":"test3","id":103,"price":10},
{"name":"test2","id":102,"price":12},
]
輸出 =
[
{"name":"test","id":101,"price":100,"qty":2},
{"name":"test3","id":103,"price":10,"qty":1},
{"name":"test2","id":102,"price":12,"qty":1},
]
uj5u.com熱心網友回復:
嘗試以下操作(當然不是最快但有效;):
let myarray = [
{"name":"test","id":101,"price":100},
{"name":"test","id":101,"price":100},
{"name":"test3","id":103,"price":10},
{"name":"test2","id":102,"price":12},
];
let groupedArray = myarray.reduce((acc, cur) => {
let foundIndex = acc.findIndex(a => a.id == cur.id);
if (foundIndex != -1){
acc[foundIndex].qty = 1
} else {
cur.qty = 1; acc.push(cur)
}
return acc;
}, []);
// groupedArray contains the grouped objects
uj5u.com熱心網友回復:
const a =[
{"name":"test","id":101,"price":100},
{"name":"test","id":101,"price":100},
{"name":"test3","id":103,"price":10},
{"name":"test2","id":102,"price":12},
];
const output = a.reduce((acc, nv, i, arr) => {
const item = acc.find(e => e.id === nv.id);
if(item) return acc;
acc.push({ ...nv, count: arr.filter(e => e.id === nv.id)?.length });
return acc;
}, []);
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/353999.html
標籤:javascript 节点.js 节点
