user3387566
user3387566

Reputation: 167

going through JSON tree to get values then print to console.log

I have some example JSON...

{
 "colors": {
        "1": {
            "name": "red", 
            "rgb_value": "255,0,0"
        }, 
        "2": {
            "name": "green", 
            "rgb_value": "0,255,0"
        }, 
        "3": {
            "name": "blue", 
            "rgb_value": "0,0,255"
        }
    }
}

Question: I would like to know how to go into "colors" then check each object ("1", "2", "3"... etc) and get the value of "name" for each one (I would like to print each one to the console with console.log). How can I do this?

Either Javascript/jQuery solutions are appreciated.

Note I cannot change the JSON as I am taking it from someone's API and have no power to re-structure their JSON so if you don't think the JSON is right, please ignore it as I have no other way.

Upvotes: 0

Views: 134

Answers (4)

Vijay Kumar
Vijay Kumar

Reputation: 345

i think this will help you. suppose your object name is data

var data = {
    "colors": {
        "1": {
            "name": "red", 
            "rgb_value": "255,0,0"
        }, 
        "2": {
            "name": "green", 
            "rgb_value": "0,255,0"
        }, 
        "3": {
            "name": "blue", 
            "rgb_value": "0,0,255"
        }
    }
}

for (key in data["colors"]) {
  console.log(data["colors"][key]["name"])
}

this time it is working now, you can copy and paste in javascript console and see the result

Upvotes: 0

Timo Virkkunen
Timo Virkkunen

Reputation: 106

Another solution in JS. Object.keys(obj.colors) returns ["1","2","3"] and forEach() loops through obj.colors["1"], obj.colors["2"] and obj.colors["3"] logging the name's value of each one of them.

Object.keys(obj.colors).forEach(function (key) {
    console.log(obj.colors[key].name);
});

Upvotes: 0

Andy
Andy

Reputation: 63524

Assuming you've parsed your JSON, a simple loop will suffice:

for (var k in obj.colors) {
  console.log(obj.colors[k].name);
}

Fiddle

Upvotes: 0

Felix
Felix

Reputation: 38102

You can use $.each() to iterate through colors of your object and get the name value:

$.each(obj.colors, function(i, val) {
    console.log(obj.colors[i].name);
});

Fiddle Demo

Upvotes: 2

Related Questions