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 

}
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]});
}
Sign up to request clarification or add additional context in comments.

Comments

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]]})

}

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.