【问题标题】:retrieving an object in a tree-like angularjs model在树状 angularjs 模型中检索对象
【发布时间】:2013-06-13 15:18:56
【问题描述】:

这是一个示例模型:

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

【问题讨论】:

  • 从逻辑的角度来看:服务于您的目的的功能可能是什么样子?
  • 好问题,我在想类似的东西:findObject(ObjectToSearchIn, searchPattern),这可以为我节省大量的 for 循环。但下面的答案看起来就像我梦寐以求的一样。

标签: javascript object angularjs


【解决方案1】:

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

【讨论】:

  • 非常感谢,看起来很棒。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-01-11
  • 1970-01-01
  • 1970-01-01
  • 2016-10-09
  • 1970-01-01
  • 1970-01-01
  • 2014-09-28
相关资源
最近更新 更多