如何汇总和分组对象数据?

时间:2020-03-23 07:56:46

标签: javascript object

如上所述,如何汇总和分组对象数据?
我尝试使用forEachObject.key()对数据进行分组。
但是我不太熟悉。
这是我的示例数据:

const srcArr =[
    {
        "1" : {
            "60" : {
                "point" : 10,
                "count" : 1
            },
            "68" : {
                "point" : 20,
                "count" : 1
            },
        }
    },
    {
        "2" : {
            "60" : {
                "point" : 100,
                "count" : 2
            }
        }
    },
    {
        "1" : {
            "88" : {
                "point" : 50,
                "count" : 1
            },
            "68" : {
                "point" : 20,
                "count" : 1
            },
        }
    },

我想要这样的数据:

{ 
  '1': { '60': { money: 10, count: 1 }, 
         '68': { money: 40, count: 2 }, 
         '88': { money: 50, count: 1 }},
  '2': { '60': { money: 100, count: 2 }}
}

2 个答案:

答案 0 :(得分:3)

尝试一下

cc = [
    {
        "1" : {
            "60" : {
                "point" : 10,
                "count" : 1
            },
            "68" : {
                "point" : 20,
                "count" : 1
            },
        }
    },
    {
        "2" : {
            "60" : {
                "point" : 100,
                "count" : 2
            }
        }
    },
    {
        "1" : {
            "88" : {
                "point" : 50,
                "count" : 1
            },
            "68" : {
                "point" : 20,
                "count" : 1
            },
        }
    }
]
const result = cc.reduce((arr, o) =>{
    let k = Object.keys(o)[0];
   arr[k] = arr[k] || {};
   let opo = o[k];
   if(arr[k]) {
    Object.keys(arr[k]).map(kk => {
      Object.keys(o[k]).map(cc => {
        if(kk === cc) {
          opo[cc] = opo[cc] || {};
          opo[cc].count =   o[k][cc].count + arr[k][kk].count;
          opo[cc].point =   o[k][cc].point + arr[k][kk].point;
        }
      });
   });
   }        
   arr[k] = {...arr[k], ...opo};    
   return arr;
}, {});

console.log(result);

这可能就是您所期望的。 忽略键命名约定:p

答案 1 :(得分:2)

我会使用Array.reduce

const srcArr = [{
    "1": {
      "60": {
        "point": 10,
        "count": 1
      },
      "68": {
        "point": 20,
        "count": 1
      },
    }
  },
  {
    "2": {
      "60": {
        "point": 100,
        "count": 2
      }
    }
  },
  {
    "1": {
      "88": {
        "point": 50,
        "count": 1
      },
      "68": {
        "point": 20,
        "count": 1
      },
    }
  }
]

let res = srcArr.reduce((arr, o) => {
  // get the key: 1,2, or 3 etc
  let k = Object.keys(o)[0];
  // create a new object with that key if it does not exist
  arr[k] = arr[k] || {};
  // push the objects
  arr[k] = Object.assign(arr[k], o[k]);
  return arr;
}, {});

console.log(res);