Reputation: 573
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')
Upvotes: 0
Views: 352
Reputation: 3223
Using grep:
thisUser = $.grep(data.users, function(e) { return e.uname==uname});
Upvotes: 1
Reputation: 15393
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;
}
});
Upvotes: 0