Traversing objects with pure JavaScript

4

I need to list objects and I have used the following function that is in jQuery. Is there an alternative to this in JavaScript only?

$.each(object, function(index, value) {
    console.log(value);
}); 
    
asked by anonymous 04.10.2015 / 16:24

3 answers

10

Basically this is it:

for (var key in object) {
    console.log(object[key]);
}

You might want to improve if you are picking up unwanted members:

for (var key in object) {
    if (object.hasOwnProperty(key)) {
        console.log(object[key]);
    }
}

Although technically to have the same semantics would have to do this:

object.forEach(function(value, index) {
    console.log(value);
});

Works in all modern browsers, but not all use a modern, use with care.

    
04.10.2015 / 16:48
8

/ p>

To iterate through an array you can use native .forEach() or a for loop if you need to support IE8.

object.forEach(function(value, index){
    console.log(value);
    // fazer mais algo com o valor
});

or for older browsers:

for (var i = 0; i < object.length; i++){
    var value = object[i];
    var index = i;   // desnecessário, mas coloquei para clarificar
    console.log(value);
}
    
04.10.2015 / 16:43
1

ecmascrip6:

 array.forEach((item)=>{
  console.log(item);                        
 });
    
25.08.2017 / 18:21