根据id转换json数组

时间:2019-05-01 20:25:15

标签: javascript json

我想根据sID和pID属性将数组转换为另一个数组 我拥有的数组是:

data = [{
 {
    "sID": 10,
     "pID": 5,
     "Sum": 9300,
     "class": "one",
    },{
    "sID": 10,
     "pID": 5,
     "Sum": 2200,
     "class": "two",
    },{
    "sID": 10,
     "pID":6 ,
     "Sum": 4600,
     "class": "one",
    },{
    "sID": 10,
     "pID": 6,
     "Sum": 5300,
     "class": "two"
    }]

我想以以下格式创建数据

[{"sID":10,"pID":5,"one":9300,"two":2200},
 {"sID":10,"pID":6,"one":4600,"two":5300}]

有没有办法做到这一点?

2 个答案:

答案 0 :(得分:1)

您可以为同一组键获取一个哈希表,然后将值的总和分配给结果。

let count = {...CATEGORIES};
var data = [{ sID: 10, pID: 5, Sum: 9300, class: "one" }, { sID: 10, pID: 5, Sum: 2200, class: "two" }, { sID: 10, pID: 6, Sum: 4600, class: "one" }, { sID: 10, pID: 6, Sum: 5300, class: "two" }],
    keys = ['sID', 'pID'],
    result = Object.values(data.reduce((h, o) => {
        var key = keys.map(k => o[k]).join('|');
        if (!h[key]) {
            h[key] = Object.assign(...keys.map(k => ({ [k]: o[k] })));
        }
        h[key][o.class] = (h[key][o.class] || 0) + o.Sum;
        return h;
    }, Object.create(null)));

console.log(result);

答案 1 :(得分:0)

更多基本信息:

const
  data = [ 
    { "sID": 10, "pID": 5, "Sum": 9300, "class": "one" }
  , { "sID": 10, "pID": 5, "Sum": 2200, "class": "two" }
  , { "sID": 10, "pID": 6, "Sum": 4600, "class": "one" }
  , { "sID": 10, "pID": 6, "Sum": 5300, "class": "two" }
  ];

var Result = [];

data.forEach(e=>{
  let idx = Result.findIndex( k=> k.sID===e.sID && k.pID===e.pID );
  if (idx<0)
  { 
    idx = Result.length;
    Result.push( { "sID":e.sID, "pID":e.pID });
  }
  Result[idx][e.class] = e.Sum;
})

console.log( Result )