Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery.each() in Node.js?

I have to loop in a JSON array to get some informations in node, but I only know how to to this using $.each() in jQuery. So I want to know if there are any alternative for the $.each jQuery function in node.js?

like image 950
Nathan Campos Avatar asked Mar 23 '12 00:03

Nathan Campos


2 Answers

You can use this

for (var name in myobject) {
   console.log(name + ": " + myobject[name]);
}

Where myobject could be your JSON data

Check out the answer here: Looping through JSON with node.js

like image 113
Hieu Van Mach Avatar answered Oct 05 '22 07:10

Hieu Van Mach


You should use the native for ( key in obj ) iteration method:

for ( var key in yourJSONObject ) {
    if ( Object.prototype.hasOwnProperty.call(yourJSONObject, key) ) {
        // do something
        // `key` is obviously the key
        // `yourJSONObject[key]` will give you the value
    }
}

If you're dealing with an array, just use a regular for loop:

for ( var i = 0, l = yourArray.length; i < l; i++ ) {
    // do something
    // `i` will contain the index
    // `yourArray[i]` will have the value
}

Alternatively, you can use the array's native forEach method, which is a tad slower, but more concise:

yourArray.forEach(function (value, index) {
    // Do something
    // Use the arguments supplied. I don't think they need any explanation...
});
like image 32
Joseph Silber Avatar answered Oct 05 '22 08:10

Joseph Silber