Traversing an array without knowing its indices

2

I have the following array:

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

I would like to access the values, but I do not know the indexes x,y,z , can you extract those values?

    
asked by anonymous 11.05.2016 / 15:16

2 answers

4

This is an 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])
}
    
11.05.2016 / 15:21
1

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

But it is possible to iterate through its properties, using Object.keys() , which converts the object into an array :

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

Reference Objects.keys () - Mozilla Developer Network

    
11.05.2016 / 16:01