Akhilesh Singh Akhilesh Singh - 5 months ago 16
Node.js Question

Search the String inside array of Objects using underscore.js

I want to search the String inside an object using underscore.js

JSON data

{ data:
[
{'id': 1, 'name': 'New Samsung Galaxy 3' },
{'id': 2, 'name': 'Samsung Grand'},
{'id': 3, 'name': 'Galaxy 3 dress new Arrival'},
{'id': 4, 'name': 'Samsung Galaxy 3 black ' },
{'id': 5, 'name': 'Samsung refrigerators'}
];
}


Let Suppose I have a keyword
Samsung Galaxy 3
. I want it return the matching string only.

Like This Output :

{ data:
[
{'id': 1, 'name': 'New Samsung Galaxy 3' },
{'id': 4, 'name': 'Samsung Galaxy 3 black ' },
];
}

Answer

Use _filter.

var data =
       [ 
         {'id': 1, 'name': 'New Samsung Galaxy 3' },
         {'id': 2, 'name': 'Samsung Grand'},  
         {'id': 3, 'name': 'Galaxy 3 dress new Arrival'}, 
         {'id': 4, 'name': 'Samsung Galaxy 3 black ' }, 
         {'id': 5, 'name': 'Samsung refrigerators'} 
        ];

    _.filter(data, function(item) { 
       return item.name.indexOf("Samsung Galaxy 3") != -1; 
    });