GDP
GDP

Reputation: 8178

How to retrieve JSON object elements with variables?

Using $.getJSON, I've got a very large result which contains elements for each of our products. I need to access some of the properties using variables, but can't manage to figure out the jQuery syntax to do so.

$.getJSON("datasource.php",function(licensed){
    // Hardcoded works
    alert ( licensed.product5200.order_id );

    // How to use a variable instead, something like this:
    var MyVar = "product5200";
    alert ( licensed.MyVar.order_id );
});

EDIT: Is there a way to determine if "product5200" exist before I begin working with it?
console.info('Is It There?:' + licensed['product5200'].hasOwnProperty);

ANSWER: console.info('Is It There?:' + licensed.hasOwnProperty('product5200'));

JSON Object (shown as a PHP array for clarity only)

[licensed] => Array
    (
        [product5200] => Array
            (
                [product_id] => 5200
                [order_id] => 159004882
            )
        [product5204] => Array
            (
                [product_id] => 5204
                [order_id] => 159004882
            )

Upvotes: 3

Views: 320

Answers (1)

Explosion Pills
Explosion Pills

Reputation: 191729

You can use array-access notation on objects as well.

licensed[MyVar].order_id

should work.

By the way, I would suggest console.log over alert, especially in Chrome (which lets you inspect the contents of the logged object).

Upvotes: 4

Related Questions