检索树状angularjs模型中的对象

时间:2013-06-13 15:18:56

标签: javascript object angularjs

以下是示例模型:

$scope.people=
   [
{"id":1, "name":"bob", "pets":[
    {"id":1, "name":"Jaco", "type":"parrot"},
    {"id":2, "name":"coco", "type":"parrot"},
    {"id":3, "name":"pluto", "type":"dog"}
    ]},
{"id":2, "name": "jason", "pets":[
    {"id":4, "name":"coco", "type":"cat"}
]},
{"id":3, "name": "kurt", "pets":[
     {"id":5, "name":"nemo", "type":"turtle"},
     {"id":6, "name":"grnx", "type":"lynx"}
]}
];

是否有angularjs / javascript函数或最佳实践来检索bob的id,或者找到动物的所有者,或者使用键/值模式提取一个宠物记录?

我想我可以编写自己的函数来查看模型(递归或for循环),但如果它们存在,我宁愿使用更高级别的方法。

1 个答案:

答案 0 :(得分:2)

您会发现querying JS data structures有多种选择。我发现linq.js非常出色。您可以使用one line of linq.js code完成每个示例。

//Get Id
return Enumerable.From($scope.people).First('$.name == "' + name + '"' ).id;            
//Pet owners
return Enumerable.From($scope.people).Where('$.pets.length > 0').Select("$.name").ToArray();            
//Pet Search
return Enumerable.From($scope.people).SelectMany('$.pets').Where('$.' + key + ' == "' + value + '"').Select('$.name').ToArray()