按键分组JSON

时间:2017-07-06 19:36:51

标签: javascript json

我已经构建了如下的JSON数据:

[
    {
        "Month": "Jan"
        "Year": 2015,
        "Count": 15
    },
    {
        "Month": "Feb"
        "Year": 2015,
        "Count": 5
    },
    {
        "Month": "Jan"
        "Year": 2016,
        "Count": 25
    },
        {
        "Month": "Feb"
        "Year": 2016,
        "Count": 50
    }
]

我想使用JavaScript对数据进行分组以获得以下输出。有人可以帮我这个吗?

[
    {
        "Month": "Jan"
        "Count_2015": 15,
        "Count_2016": 25
    },
    {
        "Month": "Feb"
        "Count_2015": 5,
        "Count_2016": 50
    }
]

2 个答案:

答案 0 :(得分:1)

您可以使用forEach()循环并将一个对象用作thisArg参数。



var data = [{"Month":"Jan","Year":2015,"Count":15},{"Month":"Feb","Year":2015,"Count":5},{"Month":"Jan","Year":2016,"Count":25},{"Month":"Feb","Year":2016,"Count":50}]  

var result = []
data.forEach(function(e, i) {
  if (!this[e.Month]) {
    this[e.Month] = {
      Month: e.Month,
      ['Count_' + e.Year]: e.Count
    }
    result.push(this[e.Month])
  } else {
    this[e.Month]['Count_' + e.Year] = e.Count
  }
}, {})

console.log(result)




答案 1 :(得分:0)

var months = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
var result = [];
[].forEach.call(months, function(month) {
  var monthObj = {"Month": month};
  result.push(monthObj);
});
let mi, year, keystr
for (var i=0; i< data.length; i++) {
  var obj = data[i];
  for (var key in obj) {
    if (!obj.hasOwnProperty(key)) continue;
    var value = obj[key];
    switch (key) {
      case "Month":
        mi = months.indexOf(value);
        break;
      case "Year":
        year = value;
        break;
      case "Count":
        keystr = "Count_" + year.toString();
        resObj = result[mi];
        resObj[keystr] = value;
        break;
    }
  }
}
console.log(result);

试试here