Traverse an array without knowing its indices

Asked

Viewed 736 times

2

I own the following array:

var array = {
    x: "Primeiro Valor",
    y: "Segundo Valor",
    z: "Terceiro Valor"
};

I would like to access the values, however, I do not know the indices x,y,z, it is possible to extract these values?

  • You need the index or only the value is important?

2 answers

4


That’s a Object, to read its properties do:

var array = {
    x: "Primeiro Valor",
    y: "Segundo Valor",
    z: "Terceiro Valor"
};

for (var prop in array) {
    console.log("propriedade: " + prop + " valor: " + array[prop])
}

  • 1

    Perfect! Thank you

1

Actually what you have there is not a array, but rather a object.

But it is possible to iterate by its properties using Object.keys(), that converts the object in a array:

Object.keys(seuObjeto).forEach(function(key,index) {
  console.log(seuObjeto[key]);
});

Reference Objects.Keys() - Mozilla Developer Network

  • No need to use the hasOwnProperty, in the definition of Object.keys it is already said that it will be done. You can look at its implementation, it already does it for you.

  • It is true, by the implementation of Mozilla this check is already being done. I repeated because I thought it might not be being, as a precaution. I will edit the answer. Thank you!

Browser other questions tagged

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