Browse objects with pure Javascript

Asked

Viewed 18,966 times

4

I need to list objects and resort to the following function which is in jQuery. There is an alternative to this only in Javascript?

$.each(object, function(index, value) {
    console.log(value);
}); 
  • 1

    You need to rotate objects is this?

  • @Pauloroberto is yes..

  • 1

    @Paul, I rejected your suggested edition because "Rotate" is not what is happening, has no object on the screen being rotated (90degrees or 180 or any other value)... certainly is a linguistic confusion, I believe that suggestion of the Edilson is the correct: "Go through" (I had not been able to think of the proper word for that $.each) -or "Iterate" as Sergio says.

3 answers

10


Basically this is it:

var objeto = [ 1, 2 ];
for (var chave in objeto) console.log(objeto[chave]);

You may want to get better if you’re picking up unwanted members:

var objeto = [ 1, 2 ];
for (var chave in objeto) if (objeto.hasOwnProperty(chave)) console.log(objeto[chave]);

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

var objeto = [ 1, 2 ];
objeto.forEach(function(valor, indice) {
    console.log(valor);
});

I put in the Github for future reference.

Works on all modern browsers, but not everyone uses a modern, use carefully.

  • The first solution helped me a lot..

8

This code alone does not run anything.
(or do you mean "iterate" and I who speak Portuguese of Portugal think you refer to axis rotation?).

To iterate an array you can use the .forEach() native or a cycle is 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);
}
  • I also get lost when I speak something different.. But what I wanted to say and left poorly expressed in the question is that it would be necessary...

  • @Elaine Sometimes the tongue gets in the way :) if you want to go through this array and use each element of the array then it’s "iterate" and that’s what my answer points to.

  • http://www.priberam.pt/dlpo/iterar. In our context, it’s usually "loop through each element of the object".

1

ecmascrip6 :

 array.forEach((item)=>{
  console.log(item);                        
 });
  • 3

    It’s always interesting to explain at least what your snippet of code does. :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.