【问题标题】:how to Group json object based on id in the object如何根据对象中的id对json对象进行分组
【发布时间】:2021-12-22 00:28:16
【问题描述】:

我需要用count将普通对象分组为单个,如何根据对象中的id对对象进行分组,以及如何在结果中添加额外的带有count的键。

 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},
            ]

【问题讨论】:

标签: javascript node.js nodes


【解决方案1】:

尝试以下方法(当然不是最快但有效;):

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

【讨论】:

    【解决方案2】:
    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;
    }, []);
    

    【讨论】:

      猜你喜欢
      • 2021-09-12
      • 2023-02-05
      • 1970-01-01
      • 1970-01-01
      • 2018-11-23
      • 1970-01-01
      • 2021-04-12
      • 2019-03-23
      • 1970-01-01
      相关资源
      最近更新 更多