2017-05-10 7 views
-2

私はJavaScriptでjsonオブジェクトリテラルを扱っています。私の元のjsonから始めるJsonオブジェクトリテラルを操作する

[{"group":"sample 1","name":"FC_TOT","value":6}, 
{"group":"sample 1","name":"PPC","value":88}, 
{"group":"sample 1","name":"PRO_OX","value":6}, 
{"group":"sample 1","name":"POLY_TOT","value":6}], 

[{"group":"sample 2","name":"FC_TOT","value":9}, 
{"group":"sample 2","name":"PPC","value":8}, 
{"group":"sample 2","name":"PRO_OX","value":7}, 
{"group":"sample 2","name":"POLY_TOT","value":7}]] 

これを名前に基づいて再ソートし、各グループに値を割り当てる必要があります。新しいJSONは新しいグループが、元のJSONから名前です

[ 
    { 
     "group": "FC_TOT", 
     "sample 1": 6, 
     "sample 2": 9 
    }, 
    { 
     "group": "PPC", 
     "sample 1": 88, 
     "sample 2":8 
    }, 
    { 
     "group": "PRO_OX", 
     "sample 1": 6, 
     "sample 2": 7 
    }, 
    { 
     "group": "POLY_TOT", 
     "sample 1": 6, 
     "sample 2": 7 
    } 
] 

のようになります。どのようにこれを達成するための任意のアイデアですか?

+0

必要性は何ですか? –

答えて

1

reduce()を使用してアレイを構築し、ループ内にループオブジェクトを1つ入れてforEach()することができます。

var data = [[{"group":"sample 1","name":"FC_TOT","value":6},{"group":"sample 1","name":"PPC","value":88},{"group":"sample 1","name":"PRO_OX","value":6},{"group":"sample 1","name":"POLY_TOT","value":6}],[{"group":"sample 2","name":"FC_TOT","value":9},{"group":"sample 2","name":"PPC","value":8},{"group":"sample 2","name":"PRO_OX","value":7},{"group":"sample 2","name":"POLY_TOT","value":7}]] 
 

 
var obj = {} 
 
//Loop main array 
 
var result = data.reduce(function(r, e) { 
 
    //Loop each group array to get objects 
 
    e.forEach(function(a) { 
 
    //Check if current object name exists as key in obj 
 
    if (!obj[a.name]) { 
 
     //If it doesn't create new object as its value and store it in obj 
 
     obj[a.name] = {group: a.name,[a.group]: a.value} 
 
     //push value of that object in result array of reduce or r 
 
     r.push(obj[a.name]) 
 
    } else { 
 
    //If it already exists in obj then assign new property to it 
 
     Object.assign(obj[a.name], {[a.group]: a.value}) 
 
    } 
 
    }) 
 
    // Return accumulator or result array 
 
    return r; 
 
}, []) 
 

 
console.log(result)

+0

これは魅力的なように働いた、ありがとう! – LeadingMoominExpert

+0

ようこそ。 –

+0

ここで何が起きているのか説明してください。それは非常に役に立ちます。前もって感謝します。 – Shubham

関連する問題