Murali Prasanth Murali Prasanth - 1 month ago 9
Javascript Question

ESLint error use Object.keys instead of for..in

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

Answer Source

When you use Object.keys with forEach to iterate through the keys, you are passing a function as callback, so the return statements are for that callback function instead of searchObj.

Instead of returning the result from the forEach callback, you can store it in an external variable (accessed inside the forEach by means of closure), assign it in the forEach, and then return its value. Here I create a variable called foundObj for that:

function searchObj (obj, query) {
  var foundObj = null;

  Object.keys(obj).forEach(function(key) {
    var value = obj[key];
    if (typeof value === 'object') {
       foundObj = searchObj(value, query);
    }
    if (typeof value === 'string' && value.toLowerCase().indexOf(query.toLowerCase()) > -1) {
       foundObj = obj;
    }
  });

  return foundObj;
}

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);