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?
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
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...
});
In nodejs I found Array.forEach(callback)
to best suite my needs. It works just like jQuery:
myItems.forEach(function(item) {
console.log(item.id);
});
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
jQuery is just javascript, you can do the loop yourself.
I don't know the structure of the JSON array you're looping but you can use a for..in method to get every property of an object.
So you would do something like:
for( var i = 0; len = jsonArray.length; i < len; i++) {
for(var prop in jsonArray[i]) {
//do something with jsonArray[i][prop], you can filter the prototype properties with hasOwnProperty
}
}
Also you can use the forEach method that Array
provides, that works in a similar way that jQuerys .each()
good luck!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.