2016-06-28 67 views
-1

对不起,如果这之前已被问过。我有JSON结构,如:按Javascript分组/格式化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

+1

{ “键”: “B”[....这种结构是无效 – brk

回答

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);

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; 
 
}