0

Is it possible to supply a variable to select a particular element within a JSON array element in order to select it?

Assuming I have many users:

"users": [
    { "id":"000000", "uname": "admin", "password": "admin", "phash": "b109f3bbbc244eb82441917ed06d618b9008dd09b3befd1b5e07394c706a8bb980b1d7785e5976ec049b46df5f1326af5a2ea6d103fd07c95385ffab0cacbc86",
        "profile": {
            "fullname"  : "Admin Admin",
            "datejoined": "01-01-2014",
            "reputation": "100",
            "displaypic": "http://www.google.com/logo.png",
            "cart": {
                "Cid" : "1000000",
                "item": [
                    { "Iid": "00000001", "quantity": "10" }
                ]
            }
        }
    },

Is it possible to select the above element by supplying just the username using jQuery?

I have tried: Note: uname in the jQuery is a variable with "admin" assigned

$.getJSON('ssUsers.json', function (data) {

        $(data.users[uname].profile.cart.item).each(function () {
            ++cartItems;
        });

With little luck:

[Error] TypeError: 'undefined' is not an object (evaluating 'data.users[uname].profile')

2
  • I could not see profile in jSON Commented Mar 27, 2014 at 12:27
  • Wouldnt it by easier (and probably the best solution) that the key users is the id of the user? : '000000' : [{...}] Commented Mar 27, 2014 at 12:31

2 Answers 2

1

Using grep:

thisUser = $.grep(data.users, function(e) { return e.uname==uname});
Sign up to request clarification or add additional context in comments.

Comments

0

Try this:

$.getJSON('ssUsers.json', function (data) {

        for(i=0; i<data.users.length ; i++){
            $(data.users[i].uname.profile.cart.item).each(function () {
                ++cartItems;

            }
        });

2 Comments

This would work, but I have many users but this would only work for the first user
But "profile" is not under "uname", That code should fail, shouldn't it ?

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.