I'm working on the below code which works perfectly fine. But, ESLint suggest to use Object.keys
instead of for..in
loop. I tried to iterate the keys
, do the search if the match found then return the object. It works with for..in
but not with Object.keys. I tried to replace forEach
with filter
but didn't work for me. Any suggestions.
function searchObj (obj, query) {
// Object.keys(obj).forEach(function(key){
for (var key in obj) {
var value = obj[key];
if (typeof value === 'object') {
return searchObj(value, query);
}
if (typeof value === 'string' && value.toLowerCase().indexOf(query.toLowerCase()) > -1) {
return obj;
}
}
}
var demoData=[
{id:1,desc:{original:'trans1'},date:'2017-07-16'},
{id:2,desc:{original:'trans2'},date:'2017-07-12'},
{id:3,desc:{original:'trans3'},date:'2017-07-11'},
{id:4,desc:{original:'trans4'},date:'2017-07-15'}
];
var searchFilter = demoData.filter(function(obj){
return searchObj(obj, 'trans1');
});
console.log(searchFilter);
here is the link JS bin