2017-01-25 11 views
0

"topic_id"でjsonオブジェクトをグループ化し、各 "topic_id"の "score"を合計したいと思います。グループと合計jsonオブジェクトjavascript

私はJSONオブジェクトを持っているこの

{ 
"topic_id": { 
    "0": 1, 
    "1": 1, 
    "6": 2, 
    "8": 2, 
    "12": 3, 
    "13": 3, 
    "18": 4, 
    "20": 4, 
}, 
    "score": { 
    "0": 1, 
    "1": 3, 
    "6": 2, 
    "8": 3, 
    "12": 3, 
    "13": 1, 
    "18": 3, 
    "20": 3, 
} 
} 

のように私の結果は誰も私を助けることができる

{ 
"topic_id" : { 
    "0" : 1, 
    "1" : 2, 
    "2" : 3, 
    "3" : 4, 
}, 
"score" : { 
    "0" : 4, 
    "1" : 5, 
    "2" : 4, 
    "3" : 6, 
} 
} 

希望する必要があります。

ありがとうございました。

答えて

1

Array#reduceメソッドを使用すると、オブジェクトを生成できます。それは働いています

var data = {"topic_id": {"0": 1, "1": 1, "6": 2, "8": 2, "12": 3, "13": 3, "18": 4, "20": 4, },"score": { "0": 1, "1": 3, "6": 2, "8": 3, "12": 3, "13": 1, "18": 3, "20": 3, }}; 
 

 
// variable for holding the index reference of id 
 
var ref = {}, 
 
    // counter variable for property name, you can avoid if you are using array 
 
    i = 0; 
 

 
console.log(
 
    // get kesy of topic_id 
 
    Object.keys(data.topic_id) 
 
    // iterate over the property names 
 
    .reduce(function(obj, k) { 
 
    // check id refernce present already 
 
    if (data.topic_id[k] in ref) { 
 
     // if present then update the score 
 
     obj.score[ref[data.topic_id[k]]] += data.score[k]; 
 
    } else { 
 
     // if not present add reference in the ref object 
 
     ref[data.topic_id[k]] = i++; 
 
     // add entry in topic_id 
 
     obj.topic_id[ref[data.topic_id[k]]] = data.topic_id[k]; 
 
     // add score value 
 
     obj.score[ref[data.topic_id[k]]] = data.score[k]; 
 
    } 
 
    // return the object reference 
 
    return obj; 
 
    // set initial value as our prefered object format 
 
    }, {topic_id: {}, score: {}}) 
 
)

+0

、そんなに先生に感謝します。 – user3726932

関連する問題