-3

I have this JSON data and I want to iterate over all objects like uf, ivp en so on.

{
"version": "1.5.0",
"autor": "mindicador.cl",
"fecha": "2018-10-31T13:00:00.000Z",
"uf": {
"codigo": "uf",
"nombre": "Unidad de fomento (UF)",
"unidad_medida": "Pesos",
"fecha": "2018-10-31T04:00:00.000Z",
"valor": 27432.1
},
"ivp": {
"codigo": "ivp",
"nombre": "Indice de valor promedio (IVP)",
"unidad_medida": "Pesos",
"fecha": "2018-10-31T04:00:00.000Z",
"valor": 28540.81
},
}

Right now I have this code but just give me the name of the objects I cannot access to properties

$.ajax({
                type: 'GET',
                url: API_REQUEST,
                dataType: 'json',
                success: function(data) {
                    $('#mindicador').html(JSON.stringify(data));
                    let k;
                    for (k of Object.keys(data)) {
                        if (k === 'version') continue;
                        if (k === 'autor') continue;
                        if (k === 'fecha') continue;
                        console.log(k.nombre);
                    }
                }
                ,error: function(jqXHR, textStatus, errorMessage) {
                    console.log('errorMessage: ' + errorMessage);
                }
            });
  • 1
    Possible duplicate of [Iterate through object properties](https://stackoverflow.com/questions/8312459/iterate-through-object-properties) – slider Oct 31 '18 at 14:44
  • `I cannot access to properties` because your asking for the keys. Have a look at `Object.entries`, this will give you the key and value. eg. `for ([k, v] of Object.keys(data))` k = key, v = value – Keith Oct 31 '18 at 14:45
  • It only gives you the names of the properties because that's explicitly what you told it to do by using `Object.keys`....anyway what do you want to do when you get to the nested objects (e.g. uf) - you want to recursively loop through all the sub-properties, or not? Is the structure predictable every time, or will you not know the property names in advance? The answers to those questions will affect how complicated the solution is. – ADyson Oct 31 '18 at 14:47

1 Answers1

1

By iterating through the Object.keys of data, you're just looking at an array of strings. If you want to access that key's value, you can access it from data with bracket notation:

for (const k of Object.keys(data)) {
    console.log(data[k]);
}

Or, instead of using Object.keys, you can iterate the object with with a for ...in loop:

for (const k in data) {
    console.log(data[k]);
}
SeanMcP
  • 293
  • 6
  • 19