最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - JSON element selection - Stack Overflow

programmeradmin2浏览0评论

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 badges
Add a ment  | 

4 Answers 4

Reset to default 4

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.

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.

发布评论

评论列表(0)

  1. 暂无评论