2016-06-28 7 views
-1

これまでにお聞きしたことがありましたら申し訳ありません。私のようなJSON構造を持っている:私は基本的にキーごとにグループ化された値にグループ化/ jsonデータをJavascriptでフォーマットする

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

をフィールドの残りの部分を兼ね備えている別の形式に変更したい

{"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"} 
]} 

私はこの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; 
 
}

関連する問題