0
family = {
  'person1':[{"id":"1111","name":"adam", "sex":"male", "born":"USA"}],
  'person2':[{"id":"2222","name":"sarah", "sex":"female", "born":"Canada"}],
  'person3':[{"id":"3333","name":"adam", "sex":"male", "born":"USA"}]
};

鉴于上面的家庭对象,我如何提取具有特定 id(或名称)值的人员对象之一的所有属性(id、姓名、性别、出生)?例如 id=1111

所以理想情况下,我可以获得一个可以操作的新对象 personInQuestion,其中:

personInQuestion = {"id":"1111","name":"adam", "sex":"male", "born":"USA"}
4

4 回答 4

4

循环遍历对象,并获取匹配的元素。

var search = 1111;

var personInQuestion = {};
for(var x in family){
    var item = family[x][0];
    if(item.id == search){
        personInQuestion = item;
        break;
    }
}
于 2012-07-24T16:10:40.503 回答
0

我不认为 jQuery 是最好的工具,相反我建议你看看Backbone 库提供的 Where 方法。不知道会不会是矫枉过正。

用法是这样的:

var friends = new Backbone.Collection([
  {name: "Athos",      job: "Musketeer"},
  {name: "Porthos",    job: "Musketeer"},
  {name: "Aramis",     job: "Musketeer"},
  {name: "d'Artagnan", job: "Guard"},
]);

var musketeers = friends.where({job: "Musketeer"});

alert(musketeers.length);
于 2012-07-24T16:11:20.287 回答
0

jQuery 不为 JSON(JavaScript 对象)数据提供选择器,因此您需要遍历对象。例如:

result =  null;
$.each(family, function(i, v) {
  if (v.id === "1111" && v.name === "adam" ...) {
    result = v;
    return;
  }
});
于 2012-07-24T16:12:31.810 回答
0

这是 Rob Hruska建议(在评论中)使用Underscore的示例。

family = {
  'person1':[{"id":"1111","name":"adam", "sex":"male", "born":"USA"}],
  'person2':[{"id":"2222","name":"sarah", "sex":"female", "born":"Canada"}],
  'person3':[{"id":"3333","name":"adam", "sex":"male", "born":"USA"}]
};

var searchId = 1111;

var person = _.find(family, function(item) { return item[0].id == searchId; })[0];
于 2012-07-25T01:57:19.053 回答