raphadko raphadko - 24 days ago 10
Javascript Question

Iterate in a javascript subobject with an unknown name

I'm parsong RSS news using javascript..
The object returned (from Yahoo YQL) has the news inside a news object.

Normally, it's inside this subobject:

news.results.item


So I would just iterate normally using:

news.results.item.forEach


Now it gets interesting when I'm loading multiple sources.. it can return stuff like

news.results.item (array[10])
news.results.entry (array[10])
news.results.banana (array[10])


My question is, how can I iterate inside these entries when I don't know the naming that will be returned.. is there a simple way to merge them all? (Using jQuery is fine)

Answer

You can loop through all of the 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 for something specific and want to stop when you find it, you can use some instead of forEach or do a nested find (you'll need a find polyfill for some browsers still).

But if you want to combine them before searching, that's fairly easily done:

var news = {
    results: {
        item: ["a", "b", "c"],
      entry: ["d", "e", "f"],
        banana: ["g", "h", "i"]
    }
};
var all = [];
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 would use reduce for that. I think it obscures rather than aiding reading in cases like this where the accumulation value never actually changes.)

Comments