0

I have a JavaScript object occurrences;

var occurrences = { "Karri" : 1, "Ismo" : 1, "Harri": 4, ........} //it has 129 elements

I want to have a JavaScript object which looks like this:

var json = [{"Researcher":"Karri","Total":1},
 {"Researcher":"Ismo","Total":1},
 {"Researcher":"Harri","Total":4},......]

Any ideas about how to do it?

I have this method where I count the total numbers and I try to create JavaScript object.

function countPublicationsPerResearcher(fullnames){
 var occurrences = { };
 var json =[];
 for (var i = 0; i < fullnames.length; i++) {
 if (typeof occurrences[fullnames[i]] == "undefined") {
 occurrences[fullnames[i]] = 1;
 json.push({ "Researcher": fullnames[i],
 "Total": occurences[fullnames[i]]
 });
 } else {
 occurrences[fullnames[i]]++;
 json.push({ "Researcher": fullnames[i],
 "Total": occurrences[fullnames[i]]
 });
 }
 }
 //console.log(JSON.stringify(occurrences));//prints the occurences Json
 console.log(JSON.stringify(json)); //prints every iteration of the for loop, not overall result 
}
asked Apr 15, 2015 at 7:18
1
  • What did you try so far? Commented Apr 15, 2015 at 7:21

2 Answers 2

4

You could use e.g. the following code:

var json = [];
for(var name in occurences){
 json.push({"Researcher":name,"Total":occurences[name]});
}
answered Apr 15, 2015 at 7:22
0

What you could do is get the keys from the occurences object and then construct your json list.

var json = [];
for (var key in occurences ) {
 if (occurences .hasOwnProperty(key)) {
 json.push({"Reseaercher" : key, "Total" : occurences[key]})
 }
}

if you are targetting only morden browsers you can do away with the check if it is a property of the object by extracting the keys using Object.keys and then pushing them into the array like this.

var json = [];
var keys = Object.keys(yourobject);
for (var i= 0; i < keys.length; i++ ) {
 json.push({"Reseaercher" : keys[i], "Total" : occurences[key[i]]})
}
answered Apr 15, 2015 at 7:28

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.