Dhruv Batra Dhruv Batra - 6 months ago 8
JSON Question

How to extract "name" and the "runs" from this list of objects

So here is have the function I made. I want to extract the

names
in an array and the
runs
of the respective teams so I can use them as a response to display them in a graph.

function unpack(obj, key){
Object.keys(obj).forEach(function(key){
var collection=[];
var collections=[];
for(var k in obj){
collection.push(obj[k]);
}
console.log(collection);
return collection;


});
}


This is the list of objects

[
{
name: "Scotland",
stats: {
runs: 16135,
wickets_taken: 1,
matches_played: 354
}
},
{
name: "Pakistan",
stats: {
runs: 70900,
wickets_taken: 43,
matches_played: 1066
}
},
{
name: "West Indies",
stats: {
runs: 61300,
wickets_taken: 280,
matches_played: 739
}
},
{
name: "Sri Lanka",
stats: {
runs: 108242,
wickets_taken: 741,
matches_played: 1049
}
}]

Answer

Let the variable in which your object is stored is obj

function getData() {
        var names = [];
        var runs = [];
        obj.forEach(function(item) {
            names.push(item.name);
            runs.push(item.stats.runs);
        });
        return {
            runs: runs,
            names: names,
        }
    }
    //access them outside as:
var data = getData();
var names = data.names; //accessing name and run array returned from fxn
var runs = data.runs;
Comments