3

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
            )

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

9 Comments

Ah...started down the path of Arrays to begin with, but as I learn this stuff, the googling gets me down a specifc path. BTW, I generally do use console - I use alert when I don't want to lose track of something I'm working on - it nags me until I finish it, lol
And thank you, btw....KevinB actually answered it first, so I have to accept his answer, but +1 for yours as a consolation! :)
@GDP it says I answered 8 minutes ago and he answered 9 minutes ago
It doesn't really matter, the question was asked, and an answer was found. :)
@Steve oh yeah; I guess I forgot how to count
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.