wildcrazy
wildcrazy

Reputation: 29

Remove falsy values in object

I'm trying to loop all the properties in an object and remove everything that are falsy, then return the object that was passed in using delete. Obviously I am doing something wrong... This is the code that I wrote so far.

var obj = {
  a: undefined,
  b: "banana",
  c: 0,
  d: false,
  e: "",
  f: "apple",
  g: 23
}

var truthy = function (obj) {
  for (var i in obj) {
  if (obj[i] === null || obj[i] === undefined) {
  delete obj[i];
  }
 } return obj;
}

This is the actual question: Make a function that takes in an object, loops through all its properties, and removes any that are falsy. Then return the object that was passed in. (hint: delete)

Upvotes: 1

Views: 3107

Answers (5)

svenema
svenema

Reputation: 2556

Not exactly what OP asked for, but related, and matches the question title. This deletes all falsy values, but returns a new object, instead of mutating the existing. This is what I generally use, if I don't need recursion.

const removeFalsy = (o: object) => {
    return Object.entries(o).reduce((a,[k,v]) => ( !v ? a : (a[k]=v, a)), {})
}

Might be useful for people stumbling on this answer, and requiring exactly this.

Upvotes: 0

Mihey Mik
Mihey Mik

Reputation: 1862

I would do _.pickBy(obj, _.identity); it will return object with only truthy values

Upvotes: 3

Jeremy Rajan
Jeremy Rajan

Reputation: 662

According to MDN, falsy means:

" A falsy value is a value that translates to false when evaluated in a Boolean context.

JavaScript uses type coercion in Boolean contexts. "

if (false)
if (null)
if (undefined)
if (0)
if (NaN)
if ('')
if (document.all) [1]

So, if you want to delete all falsy values then, change the condition to if (!obj[i]) which checks for falsy values and removes in next line.

refer:

  1. JsFiddle: https://jsfiddle.net/tk589h2s/
  2. Article: https://developer.mozilla.org/en-US/docs/Glossary/Falsy

Upvotes: 0

Tiep Phan
Tiep Phan

Reputation: 12596

demo here:

var obj = {
  a: undefined,
  b: "banana",
  c: 0,
  d: false,
  e: "",
  f: "apple",
  g: 23
}

var truthy = function (obj) {
  for (var i in obj) {
    if (!obj[i]) {
      delete obj[i];
    }
  }
  return obj;
};
console.log(truthy(obj));

because you use === so null ('') not equal to false, your code just remove key with false and undefined.

Upvotes: 0

Matti Virkkunen
Matti Virkkunen

Reputation: 65156

  1. Returning the object is redundant because you're modifying the object that was passed in. If you want to return a new object with properties filtered out, make a new object in the function and copy the properties you want to leave in into it.
  2. Your definition of "falsy" isn't exactly in line with JavaScript's. If you want the same "falsy" as everywhere else, just say if (!obj[i]). Assuming that's what you want of course, but not considering false "falsy" is a bit silly.

What was your actual problem though?

Upvotes: 5

Related Questions