0

I would like to group json object by "topic_id" and sum "score" of each "topic_id".

I have json object like this

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

My result should be

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

Hope anyone can help me.

Thank so much.

1 Answer 1

2

You can use Array#reduce method to generate the object.

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: {}})
)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.