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,name,sex,born)?例如id = 1111
理想情况下,我可以获得一个我可以操作的新对象personInQuestion,其中:
personInQuestion = {"id":"1111","name":"adam", "sex":"male", "born":"USA"}
答案 0 :(得分:4)
遍历对象,并抓取匹配的元素。
var search = 1111;
var personInQuestion = {};
for(var x in family){
var item = family[x][0];
if(item.id == search){
personInQuestion = item;
break;
}
}
答案 1 :(得分:0)
我不认为jQuery是最好的工具,相反我建议你看看at the Where method that the Backbone library offers。不确定它是否有点矫枉过正。
用法是这样的:
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);
答案 2 :(得分:0)
jQuery不为JSON(JavaScript Object)数据提供选择器,因此您需要迭代该对象。例如:
result = null;
$.each(family, function(i, v) {
if (v.id === "1111" && v.name === "adam" ...) {
result = v;
return;
}
});
答案 3 :(得分:0)
以下是Rob Hruska的suggestion(在评论中)使用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];