Reputation: 29
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
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
Reputation: 1862
I would do _.pickBy(obj, _.identity);
it will return object with only truthy values
Upvotes: 3
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:
Upvotes: 0
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
Reputation: 65156
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