Reputation: 136
Below is the nested object named data. Here I want to display all the objects keys and values. For that I have written a code which is below:
var data = {
response: {
deals: [
{
id: 1,
color: {
id: 608290
}
}
]
}
};
Using below code I have reached to access object deal's "id" that is key and its value that is 1 but gives [object object ] for color, because it has its own key and value i.e id:608290. I want to display it too. Please make some change to code to get that key and value too of color object inside of deals.
for(var i = 0; i <= data.response.deals.length-1;i++){
$.each( meta.response.deals[i], function( key, value ) {
alert( key + ": " + value );
});
Upvotes: 0
Views: 379
Reputation: 48211
You could use a recursive function like this:
function deepTraverse(obj, indent) {
var str = "";
for (var key in obj) {
var newIndent = indent + " "; // <-- for formatting only
str += newIndent + key + ": ";
str += (typeof obj[key] != "object")
? obj[key] + "<br />"
: "<br />" + deepTraverse(obj[key], newIndent);
if (typeof obj[key] != "object") {
alert(key + ": " + obj[key]);
}
}
return str;
}
See also this short demo.
Upvotes: 0
Reputation: 2949
This code will run through the object's array. Withing the loop you can do whatever you want to do with the deals.
var data = {
response: {
deals: [{
id: 1,
color: { id: 608290 }
},
{ id: 2,
color: { id: 123456 }
},
{ id: 9001,
color: { id: 456789 }
}]
}
};
for (var i in data.response.deals) {
var obj = data.response.deals[i];
console.log(obj);
// obj.id => current ID
// obj.color.id => color's ID
}
Log:
{"color": {"id": 608290}, "id": 1}
{"color": {"id": 123456}, "id": 2}
{"color": {"id": 456789}, "id": 9001}
Live example: http://jsbin.com/ipeful/4
Upvotes: 1
Reputation: 3204
Try this
$.each(data.response.deals, function(index, item)
{
//item is the object you have in the array
//item.id ==> The id value in the object
//item.color.id ==> The id value in the color object
});
Upvotes: 0
Reputation: 7375
var data = { metal: { deals: [ { id: 1, color: { id: 608290 } } ] } };
$.each(metal.deals,function(index,item){
$.each(item,function(itemIndex,value)
{
//process your sub items
});
});
Thanks,
Siva
Upvotes: 0
Reputation: 636
$.each(data.metal.deals,function(i,item){
// alert("id:"+item.id+" color:"+item.color.id);
});
Upvotes: 0