Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 514
fearhsonic Avatar asked Mar 28 '14 09:03

fearhsonic


People also ask

How do I iterate through a JSON object?

Use Object.values() or Object. entries(). These will return an array which we can then iterate over. Note that the const [key, value] = entry; syntax is an example of array destructuring that was introduced to the language in ES2015.

How do I iterate through a nested array of objects in JavaScript?

You can create a function to loop through nested objects. That function automatically will check for nested objects and go through that objects. The for...in loop and Object. keys() method return keys/properties of the object.

Can JSON arrays be nested?

Objects can be nested inside other objects. Each nested object must have a unique access path. The same field name can occur in nested objects in the same document.


1 Answers

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);
});
like image 139
Gabriel Llamas Avatar answered Oct 14 '22 18:10

Gabriel Llamas