Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve JSON object elements with variables?

Tags:

jquery

getjson

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
            )
like image 556
GDP Avatar asked May 26 '26 13:05

GDP


1 Answers

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).

like image 148
Explosion Pills Avatar answered May 30 '26 15:05

Explosion Pills



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!