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?
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?
Share Improve this question edited Dec 30, 2019 at 12:54 Mickael Lherminez 6951 gold badge11 silver badges30 bronze badges asked Dec 28, 2009 at 18:01 amitamit 10.2k23 gold badges76 silver badges125 bronze badges4 Answers
Reset to default 4What 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.
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
"
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.
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.