Reputation: 157
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
}
Upvotes: 0
Views: 61
Reputation: 1207
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]]})
}
Upvotes: 0
Reputation: 567
You could use e.g. the following code:
var json = [];
for(var name in occurences){
json.push({"Researcher":name,"Total":occurences[name]});
}
Upvotes: 4