Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
150
rated 0 times [  153] [ 3]  / answers: 1 / hits: 6605  / 10 Years ago, wed, september 3, 2014, 12:00:00

I am using UnderscoreJs in my project. I have to filter an array containing object having properties. I need to filter based on the values. The value can be of any property of the object. ex: mini should fetch both toyota and Honda since mini is present as part of both the objects



[{ name:Toyota minivan, id:506, size: large }, { name:Honda Civic, id:619, size: mini }]


How to do using Underscore. I have tried the following approach but not working.



var searchStr=mini;
var evens = _.filter([arrayData], function(obj){ return _.contains(obj, searchStr); });


Can you please let me know where I am going wrong?


More From » arrays

 Answers
4

_.contains only works on arrays, so you need to grab the values from each object first and then check if any of them contain the search string. I've used some in this example, together with indexOf to match the string.



var searchStr=mini;
var mini = _.filter(arr, function (obj) {
return _.values(obj).some(function (el) {
return el.indexOf(searchStr) > -1;
});
});


DEMO


[#42738] Tuesday, September 2, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
louiseb

Total Points: 368
Total Questions: 107
Total Answers: 107

Location: Tanzania
Member since Wed, Feb 24, 2021
3 Years ago
;