Q:

Guard against filtering an empty JS object

I have the following code:
for (var key in obj) {
  if (obj.hasOwnProperty(key)) {
    if (obj[key].id === foo.id) {
      // do something
    }
  }
}

I'm checking whether the object is not empty before doing any functionality, because the array is populated later on user interaction.
For better readability, I want to do something like this:
const result = obj.filter((item) => item.id === foo.id)
return result[0]

This, however, will produce an error: obj.filter is not a function since the object is empty when the page renders and is populated later.
Question is - how do I simplify this and at the same time guard against filtering the empty object in the most simple way?

EDIT: Adding sample data structure for obj
{
    0: { id: 2, name: 'John', category: 'Repair' },
    1: { id: 3, name: 'William', category: 'Maintenance' }
}

A:

You could use an empty array as default value.
const result = (obj || []).filter(item => item.id === foo.id);

or use an explicit check with Array.isArray.
const result = Array.isArray(obj) && obj.filter(item => item.id === foo.id);

The result is either an array or false.
If you like to get an empty array, you could use an array as default value as well, like
const result = Array.isArray(obj) && obj.filter(item => item.id === foo.id) || [];

Now, after giving the structure of the object, you could use 

var getItem = (obj, id) => obj && typeof obj === 'object' && Object
        .keys(obj)
        .filter(key => obj[key].id === id)
        .map(key => obj[key]),
    obj = {
        0: { id: 2, name: 'John', category: 'Repair' },
        1: { id: 3, name: 'William', category: 'Maintenance' }
    },
    result1 = getItem(obj, 3),
    result2 = getItem(null, 3);

console.log(result1);
console.log(result2);
.as-console-wrapper { max-height: 100% !important; top: 0; }

