views:

68

answers:

4

my JSON objects look like this:

[{"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"}]

As you can see the names are differentiated through their associated aid's. Now suppose I want to display the name stacked with aid: 4. what js should i write for that?

+1  A: 

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"

Pascal MARTIN
A: 

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.

Priyank
+3  A: 

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.

Jeff Beck
A: 

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.

watain