我目前在DOM中传递来自Rail的JSON数据。它看起来像这样:
> gon.posts
[
{ id: 1, name: "Post 1", related_post_ids: [3] },
{ id: 2, name: "Post 2", related_post_ids: [2, 3] },
{ id: 3, name: "Post 3", related_post_ids: [1, 2] }
]
我如何能够编写一些AngularJS(我的红宝石)以便我可以执行这个伪代码:
// Using "Post 1" and mapping to its related posts.
> gon.posts[0].related_posts
[
{ id: 3, name: "Post 3", related_post_ids: [1, 2] }
]
// Then being able to do this recursively to make development with the JSON easier:
> gon.posts[0].related_posts[0].related_posts
[
{ id: 1, name: "Post 1", related_post_ids: [3] },
{ id: 2, name: "Post 2", related_post_ids: [2, 3] }
]
如果您可以通过AngularJS的map
或each
函数展示如何执行此操作,也会有所帮助。
用户评论说Array.prototype.filter()
会很有用,但我并不是在寻找一个重要的解决方案,而是通过AngularJS寻找最好的,最小的DRYest解决方案。
Ember Data有find()
方法。如果我能够使用Ember并加载数据,我将能够轻松搜索,但我仍然需要JS中的ActiveRecord::Proxy
对象之类的东西能够处理委托和我不确定如何在JS中编写新的对象类型。