Grab Dynamic Element in JSON

Asked

Viewed 249 times

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 visa, can be changed depending on the call but only this object, can come as Bradesco, Itau, etc.

There is a way to access the information of this object without being 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);

1 answer

3


There is a way yes. First you can find out which is key of the object in obj.installments using for. in. Thus, regardless of what is there (visa, master, etc.) will be saved in a variable. Then it is possible to access this key by square 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);

Browser other questions tagged

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