Skip to content Skip to sidebar Skip to footer

JSON Element Selection

My JSON objects look like this: [{ 'aid': '1', 'atitle': 'Ameya R. Kadam' }, { 'aid': '2', 'atitle': 'Amritpal Singh' }, { 'aid': '3', 'atitle': 'Anwar Syed' }, { 'ai

Solution 1:

What I would suggest is modify the JSON if possible to use the AID as the key for the list of objects instead of just sending a list. If you can't change the JSON I would put the objects into an associative array using there AID as the key so you can directly get to the objects as needed.


Solution 2:

You could loop over the elements of your array, testing, for each one, if its aid is 4 :

var list = [{"aid":"1","atitle":"Ameya R. Kadam"},
        {"aid":"2","atitle":"Amritpal Singh"},
        {"aid":"3","atitle":"Anwar Syed"},
        {"aid":"4","atitle":"Aratrika"},
        {"aid":"5","atitle":"Bharti Nagpal"}
    ];
var length = list.length;
var i;
for (i=0 ; i<length ; i++) {
    if (list[i].aid == 4) {
        alert(list[i].atitle);
        break; // Once the element is found, no need to keep looping
    }
}

Will give an alert with "Aratrika"


Solution 3:

you can simple do

var someValue = [{
  "aid": "1",
  "atitle": "Ameya R. Kadam"
}, {
  "aid": "2",
  "atitle": "Amritpal Singh"
}, {
  "aid": "3",
  "atitle": "Anwar Syed"
}, {
  "aid": "4",
  "atitle": "Aratrika"
}, {
  "aid": "5",
  "atitle": "Bharti Nagpal"
}];
console.log(someValue[3]["atitle"]);

This should give you "Aratrika"

Alternatively you could loop and iterate through all objects.


Solution 4:

The only thing you can do (as far as I know), is searching for the aid:4 pair using a for loop:

a = [ /* data here ... */ ];
for (var i = 0; i < a.length; i++) {
    if (a[i].aid == 4) {
        name = a[i].name;
        break;
    }
}

I don't think there's an easier way to do that.


Post a Comment for "JSON Element Selection"