[英]Find a group of objects in JSON
[
{"id":1,"id_parent":7,"name":"sub category of cat 7-1"},
{"id":2,"id_parent":7,"name":"sub category of cat 7-2"},
{"id":3,"id_parent":8,"name":"sub category of cat 8-1"},
{"id":4,"id_parent":8,"name":"sub category of cat 8-2"}
]
I want to find a group of objects in a bigger group. 我想在一个更大的组中找到一组对象。 For example, just get objects that have id_parent=7.
例如,只需获取id_parent = 7的对象。 Now I use a for loop to do that, but I wonder there is any alternative solution to do that.
现在我使用for循环来做到这一点,但我想知道有任何替代解决方案来做到这一点。 Thank you
谢谢
If your browser has Array.filter
, you could do this: 如果您的浏览器有
Array.filter
,您可以这样做:
var children_of_7 = data.filter(function(item) {
return item.id_parent === 7;
});
If your browser doesn't have it natively, you could shim it . 如果您的浏览器本身没有它,您可以填充它 。
If you have a browser that provides ECMAScript 5th Edition implementation, than you indeed can do: 如果您有一个提供ECMAScript 5th Edition实现的浏览器,那么您确实可以这样做:
var filteredResults = data.filter(function(item) {
return item.id_parent === 7;
});
otherwise your good ole loop is the solution: 否则你的好的循环就是解决方案:
var filteredResults = [];
for (var i = 0, l = data.length; i < l; i++) {
if (data[i].id_parent === 7) {
filteredResults.push(data[i]);
}
}
Keep in mind, however, that, at least AFAIK, filter
has performance penalty. 但请记住,至少AFAIK,
filter
会降低性能。
I've mustered up some quick test for reference - can be seen here . 我已经集中了一些快速测试供参考 - 可以在这里看到。
and the difference is substantial. 而且差别很大。
No, there isn't. 不,没有。 All you can do is loop through your JSON.
你所能做的只是循环你的JSON。
underscore.js offers some interesting search capabilities: underscore.js提供了一些有趣的搜索功能:
http://documentcloud.github.com/underscore/ http://documentcloud.github.com/underscore/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.