javascriptobjectfor-in-loop

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)


Solution

    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?