在Javascript中分组/格式化json数据

时间:2016-06-28 15:57:38

标签: javascript html json grouping

很抱歉,如果之前有人询问过。我有JSON结构,如:

{"data":[
   {"Date":"03/04/2016","Key":"A","Values":"123"},
   {"Date":"04/04/2016","Key":"A","Values":"456"},
   {"Date":"03/04/2016","Key":"B","Values":"789"},
   {"Date":"04/04/2016","Key":"B","Values":"012"}
]} 

我想将其更改为其他格式,该格式基本上按键分组,并将值的其余部分组合在一起

{"Result":[
   {
     "Key":"A"
     "Values":[["03/04/2016","123"], ["04/04/2016","456"]]
    },      
   {"Key":"B"
     "Values":[["03/04/2016","789"]},["04/04/2016","012"]]
     }
]}

我想这样做javascript / html

2 个答案:

答案 0 :(得分:0)

如果不存在,您可以迭代并构建一个新对象。



var object = { "data": [{ "Date": "03/04/2016", "Key": "A", "Values": "123" }, { "Date": "04/04/2016", "Key": "A", "Values": "456" }, { "Date": "03/04/2016", "Key": "B", "Values": "789" }, { "Date": "04/04/2016", "Key": "B", "Values": "012" }], result: [] };

object.data.forEach(function (a) {
    if (!this[a.Key]) {
        this[a.Key] = { Key: a.Key, Values: [] };
        object.result.push(this[a.Key]);
    }
    this[a.Key].Values.push([a.Date, a.Values]);
}, Object.create(null));

console.log(object);




答案 1 :(得分:0)

我认为这可以是一个更好的答案(但Nina的答案是您的问题条款的匹配)如果数据数据项具有不同的属性而您不想更改输入数据。



var raw = {"data":[
   {"Date":"03/04/2016","Key":"A","Values":"123"},
   {"Date":"04/04/2016","Key":"A","Values":"456"},
   {"Date":"03/04/2016","Key":"B","Values":"789"},
   {"Date":"04/04/2016","Key":"B","Values":"012"}
]};

var result = new Map;
raw.data.forEach(entry => {
  var key = entry.Key;
  if (this[key])
    return this[key].push(getClonedData(entry));

  this[key] = [getClonedData(entry)];
  result.set(key, {
    Key: key,
    Values: this[key]
  })
}, Object.create(null));

var filtered = {
  result: [...result.values()]
}
console.log(filtered);

function getClonedData(entry) {
  data = Object.assign({}, entry);
  delete data.Key;
  return data;
}