javascript - 在树状 angularjs 模型中检索对象

标签 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 循环),但如果存在更高级别的方法,我宁愿使用它们。

最佳答案

您会发现 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/

相关文章:

javascript - 使用预编译模板创建页面

javascript - 如何减少写 'this' 的次数?

PHP 变量到 Javascript 变量

javascript - 如何在自定义Object.prototype.xxx函数中获取对象本身?

javascript - 将带有函数的 JSON 对象发送到另一个指令的 Controller

javascript - 使用 React 和 react-fa 在输入文本背景上动态放置一个 Font Awesome 图标

javascript - JavaScript 数组中的对象

javascript - 为什么是 {key : "value"} different from {"key" : "value"}?

JavaScript - 比较两个相同的字符串但它们不相等

javascript - 我想使用 ng-if 跳过 ng-repeat 中的项目