组和总和json对象javascript

时间:2017-01-25 04:11:23

标签: javascript angularjs arrays object

我想通过" topic_id"对json对象进行分组。和总和"得分"每个" topic_id"。

我有像这样的json对象

$login_time = time ();   // when user logs in  

$logout_time = time ();   // when user logs out 

$duration = $logout_time - $login_time;          // duration of login

我的结果应该是

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

希望有人能帮助我。

非常感谢。

1 个答案:

答案 0 :(得分: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: {}})
)