Reputation: 28324
I have this object and I want to get the portalname. How would I do that, using JS or jQuery
OBJECT
var Test = {};
Test.Customers = [{"CustomerItems":
"Portals":
{"id":"1","customer":"1950","resident":"yes",
"CustomPortals":
[
{"id":"11","test":"4251","portalname":"tye.jpg"},
{"id":"12","test":"4251","portalname":"Lsdf.jpg"},
{"id":"13","test":"4251","portalname":"nick.jpg"}
]
}
},
{"CustomerItems":
"Portals":
{"id":"2","customer":"1952","resident":"yes",
"CustomPortals":
[
{"id":"14","test":"4252","portalname":"Chrysanthemum2.jpg"},
{"id":"15","test":"4255","portalname":"navagin.jpg"},
{"id":"16","test":"4257","portalname":"jasoria.jpg"}
]
}
},
{"CustomerItems":
"Portals":
{"id":"3","customer":"1950","resident":"yes",
"CustomPortals":
[
{"id":"17","test":"4231","portalname":"Zsryanmum1.jpg"},
{"id":"18","test":"4651","portalname":"Ltd1.jpg"},
{"id":"19","test":"4281","portalname":"ser1.jpg"}
]
}
}
]
TRIED
$.each(Test.Customers, function(index, value) {
$.each(value.CustomPortals, function(innerIndex, innerValue) {
alert('File ' + innerValue + ' in customer ' + innerIndex);
});
});
But it doesn't work
Upvotes: 1
Views: 85
Reputation: 413826
Your inner ".each()" loop needs to traverse "CustomerItems.Portals" to get to "CustomPortals":
$.each(value.CustomerItems.Portals.CustomPortals, function(innerIndex, innerValue) {
alert('File ' + innerValue + ' in customer ' + innerIndex);
});
It'd probably be a good idea to add some existence tests, but you know your data better than I do.
edit — @justkt has a really good point - that JSON is, as posted here, not valid in the first place. Thus what I wrote above would be true if the stuff could be parsed :-)
Upvotes: 3
Reputation: 14766
When I ran your object through JSONLint (while I know that JSON is stricter than JS objects, it is an easy validator), it complained about this syntax:
"CustomerItems" : "Portals" : {}
By removing the "Portals" and instead setting:
"CustomerItems" : {}
and using the JS below:
$.each(Test.Customers, function(index, value) {
$.each(value.CustomerItems.CustomPortals, function(innerIndex, innerValue) {
alert('File ' + innerValue.portalname + ' in customer ' + innerValue.id);
});
});
I was able to get a working iterator that you can see in action here.
Upvotes: 2
Reputation: 69954
Try
alert('File ' + innerValue.portalname + ' in customer ' + innervalue.id);
instead of
alert('File ' + innerValue + ' in customer ' + innerIndex);
Upvotes: 2