5

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.

2 Answers 2

10

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);
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for prompt response.
2

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.

1 Comment

Thanks for providing alternative methods. I shall follow up and have a read.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.