fearhsonic
fearhsonic

Reputation: 93

Nodejs - Correct way to iterate through nested JSON array

Consider the following sample JSON array:

[{
    info: {
        refOne: 'refOne',
        refTwo: [{
            refOne: 'refOne',
            refTwo: 'refTwo'
        }]
    }
}, {
    info: {
        refOne: 'refOne',
        refTwo: [{
            refOne: 'refOne',
            refTwo: 'refTwo'
        }]
    }
}]

The above JSON is a simple representation of a database query response, What is the correct way within Nodejs to loop through each 'refTwo' array within the parent info array?

sudo example: for each item in sample JSON for each refTwo item in current item do something

I have a suspicion that the 'async' lib may be required here but some advice is much appreciated.

Upvotes: 5

Views: 12588

Answers (2)

Otze
Otze

Reputation: 102

You could use underscore or lodash to do it in a functional way.

For example have a look at Collections.each and Collections.map:

var _ = require('underscore');

var result = // your json blob here

var myRefs = _.map(results, function(value, key) {
  return value.info.refTwo;
};
// myRefs contains the two arrays from results[0].info.refTwo from results[1].info.refTwo now

// Or with each:
_.each(results, function(value, key) {
  console.log(value.info.refTwo);
}

// Naturally you can nest, too:
_.each(results, function(value, key) {
  _.each(value.info.refTwo, function(innerValue) { // the key parameter is optional
    console.log(value);
  }
}

Edit: You can of course use the forEach method suggested by Gabriel Llamas, however I'd recommend having a look at underscore nonetheless.

Upvotes: 2

Gabriel Llamas
Gabriel Llamas

Reputation: 18427

This is a simple javascript question:

var o = [...];

var fn = function (e){
    e.refOne...
    e.refTwo...
};

o.forEach (function (e){
    e.info.refTwo.forEach (fn);
});

Upvotes: 10

Related Questions