3

In JavaScript you have the nice .filter method to remove null or falsy values from arrays. So far I haven't been able to find a method to remove the same from JavaScript Objects.

Why would this be?

Currently you can create a function for arrays like :

function stripNulls(arr) {
   return arr.filter(Boolean);
}

Is there a similar function that can be created for JS Objects, or is the way filter works not practical on JS Objects.

5
  • There are no enumerables for objects like there are arrays. A for...in loop is your only option Commented Feb 7, 2018 at 2:49
  • 2
    The current answer is in-place. Would you prefer a method that does not mutate like your corollary with arrays above? Commented Feb 7, 2018 at 3:03
  • 3
    Not really related, but your function's name is really misleading. Commented Feb 7, 2018 at 3:10
  • How are you using these objects that you want to "filter"? Commented Feb 7, 2018 at 4:09
  • github.com/samverschueren/obj-clean Commented Feb 7, 2018 at 4:26

4 Answers 4

4

The answer to "can I do x to an object" (or an array for that matter) is usually "yes" and it frequently involves some form of reduce.

If you want to filter falsy values you could do something like this:

function filterFalsy(obj) {
  return Object.keys(obj).reduce((acc, key) => {
    if (obj[key]) {
      acc[key] = obj[key]
    }

    return acc
  }, {})
}

const testObj = {
  a: 'test',
  b: 321,
  c: false
}

console.log(filterFalsy(testObj))

This returns a new object without falsy values and leaves the existing object alone.

Sign up to request clarification or add additional context in comments.

2 Comments

I prefer this implementation to mine. I suggested an edit to give a snippet just for proof of concept.
That's fine. Made a couple slight style tweaks.
1

WARNING: There are better answers provided here. Also, thanks to comments made below user's should be warned using delete may provide suboptimal performance.

Filtering invalid values is a little more complex in objects. At face value this will do what you want:

var arr = [ 'apple', 43, false ];
var trueArr = arr.filter(Boolean);

console.log(trueArr);

var obj = { 'title': 'apple', 'id': 43, 'isOrange': false, 'test': 'asd' };
Object.keys(obj)
  .filter(key => !obj[key])
  .forEach(key => delete obj[key]);

console.log(obj);

However, this will not iterate over child objects / functions. This logic also directly modifies the original object (which may or may not be desired).

That can easily changed by adding this logic to a function like so:

function removeFalseyProperties(obj) {
  Object.keys(obj)
    .filter(key => !obj[key])
    .forEach(key => delete obj[key]);
    
  return obj;
}

var testObj = { 'title': 'apple', 'id': 43, 'isOrange': false, 'test': 'asd' };
var trutheyObj = removeFalseyProperties(testObj);

console.log(trutheyObj);

3 Comments

Avoid delete!
@Bergi why should we avoid delete?
Fair enough, I'll add an edit to sway users to Mark's answer and mention potential delete performance issues.
0

If you have lodash installed in your project, you can simply use

import _ from 'lodash';

_.pickBy(obj, Boolean)

Comments

-1

falsy values are 0, undefined, null, false, etc.

myArray
    .map(item => {
        // ...
    })
    // Get rid of bad values
    .filter(Boolean);

By passing Boolean we can remove all the falsy values.

1 Comment

question was about objects, not arrays

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.