这是一个示例模型:
$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 循环),但如果存在更高级别的方法,我宁愿使用它们。
最佳答案
您会发现 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()
关于javascript - 在树状 angularjs 模型中检索对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17090846/