admin管理员组文章数量:1386947
I want to get all values, where the category.id = 1 so i should get 2 results
My JSON looks like this:
var test = [
{
"id": 1,
"name": "name1",
"value": "value1",
"category": {
"id": 1,
"name": "category1"
}
},
{
"id": 2,
"name": "name2",
"value": "value2",
"category": {
"id": 1,
"name": "category1"
}
},
{
"id": 3,
"name": "name3",
"value": "value3",
"category": {
"id": 2,
"name": "category2"
}
}
];
my JavaScript looks like this:
var x = _.filter(test,
function (innerObject) {
return _.filter(innerObject,
function (category) {
return category.id === 1;
});
});
console.log(x);
I made a JS Fiddle but i get everytime all 3 elements back... not only the 2 correct ones!
I tried also something like
var x = _.where(test, {"category":{"id":2}});
console.log(x);
what seems to be logical for me, but the array is always empty
another jsFiddle
I hope somebody can tell me what i made wrong...
Thank You!
I want to get all values, where the category.id = 1 so i should get 2 results
My JSON looks like this:
var test = [
{
"id": 1,
"name": "name1",
"value": "value1",
"category": {
"id": 1,
"name": "category1"
}
},
{
"id": 2,
"name": "name2",
"value": "value2",
"category": {
"id": 1,
"name": "category1"
}
},
{
"id": 3,
"name": "name3",
"value": "value3",
"category": {
"id": 2,
"name": "category2"
}
}
];
my JavaScript looks like this:
var x = _.filter(test,
function (innerObject) {
return _.filter(innerObject,
function (category) {
return category.id === 1;
});
});
console.log(x);
I made a JS Fiddle but i get everytime all 3 elements back... not only the 2 correct ones!
I tried also something like
var x = _.where(test, {"category":{"id":2}});
console.log(x);
what seems to be logical for me, but the array is always empty
another jsFiddle
I hope somebody can tell me what i made wrong...
Thank You!
2 Answers
Reset to default 4This should work:
var x = test.filter(function (a) {return a.category.id === 1 })
That's because with where you're searching for an element that is EXACTLY like {"category":{"id":1}}
and your object is {"category":{"id":1,"name":"category1"}}
Try
_.filter(test, function(a){ return a.category && a.category.id === 1; });
本文标签: javascriptUnderscorejsfiltering in a nested JsonStack Overflow
版权声明:本文标题:javascript - Underscore.js - filtering in a nested Json - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744542236a2611681.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论