Get Dynamic Element in JSON

3

I have the following json

{
    "error": false,
    "installments": {
        "visa": [{
            "quantity": 1,
            "installmentAmount": 500.00,
            "totalAmount": 500.00,
            "interestFree": true
        }, {
            "quantity": 2,
            "installmentAmount": 261.28,
            "totalAmount": 522.55,
            "interestFree": false
        }]
    }
}

This object aims, can be changed depending on the call but only this object, can come as bradesco, itau, etc.

Is there a way to access the information for this object other than by its explicit name (installments.visa)?

Somehow play on a variable like this:

var cartao = installments.(truquemagico);

And access the data like this:

console.log(cartao[0].totalAmount);
    
asked by anonymous 02.01.2017 / 20:20

1 answer

3

There is a yes way. First you can find out what is the key of the object in obj.installments using for..in . That way, regardless of what is there (visa, master, etc) will be saved in a variable. Then it is possible to access this key by the brackets [] , getting obj.installments[prop] - where prop is the key that was discovered.

var obj = {
    "error": false,
    "installments": {
        "visa": [{
            "quantity": 1,
            "installmentAmount": 500.00,
            "totalAmount": 500.00,
            "interestFree": true
        }, {
            "quantity": 2,
            "installmentAmount": 261.28,
            "totalAmount": 522.55,
            "interestFree": false
        }]
    }
}

// descobrir a key
var prop;
for (property in obj.installments){
  prop =  property;
}

console.log(obj.installments[prop][0].totalAmount);
    
02.01.2017 / 20:26