Iterate in a javascript subobject with an unknown name -
this question has answer here:
- getting javascript object key list 11 answers
i'm parsong rss news using javascript.. object returned (from yahoo yql) has news inside news object.
normally, it's inside subobject:
news.results.item
so iterate using:
news.results.item.foreach
now gets interesting when i'm loading multiple sources.. can return stuff like
news.results.item (array[10]) news.results.entry (array[10]) news.results.banana (array[10])
my question is, how can iterate inside these entries when don't know naming returned.. there simple way merge them all? (using jquery fine)
you can loop through of array properties on news.results
:
var news = { results: { item: ["a", "b", "c"], entry: ["d", "e", "f"], banana: ["g", "h", "i"] } }; object.keys(news.results).foreach(function(key) { var value = news.results[key]; if (array.isarray(value)) { value.foreach(function(entry) { console.log(entry); }); } });
and if you're looking specific , want stop when find it, can use some
instead of foreach
or nested find
(you'll need find
polyfill browsers still).
but if want combine them before searching, that's done:
var news = { results: { item: ["a", "b", "c"], entry: ["d", "e", "f"], banana: ["g", "h", "i"] } }; var = []; object.keys(news.results).foreach(function(key) { var value = news.results[key]; if (array.isarray(value)) { all.push.apply(all, value); } }); all.foreach(function(entry) { console.log(entry); });
(some people use reduce
that. think obscures rather aiding reading in cases accumulation value never changes.)
Comments
Post a Comment