Underscore.js - filtering in nested Json

I want to get all values ​​where category.id = 1, so I have to 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 did a JS Fiddle but every time I return all 3 items ... not just 2 correct ones!

I also tried something like

var x = _.where(test, {"category":{"id":2}});
console.log(x);

      

what seems logical to me, but the array is always empty

another jsFiddle

I hope someone tells me what I did wrong ...
Thanks!

+1


source to share


2 answers


This is because where you are looking 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; });

      

+2


source


This should work:



var x = test.filter(function (a) {return a.category.id === 1 })

      

+3


source







All Articles