JavaScript by Radu TM • June 21, 2022
const removeNullAndUndefinedValuesFromObject = obj => {
// return a new object with only the truthy values
return Object.keys(obj)
.filter(key => obj[key])
.reduce((acc, key) => {
// copy each truthy value to the new object
acc[key] = obj[key];
return acc;
}, {});
};
// given this object
const obj = {
a: 1,
b: null,
c: undefined,
d: 'hi'
};
console.log(removeNullAndUndefinedValuesFromObject(obj));
// { a: 1, d: 'hi' }
0
25.550
JavaScript by Radu TM • June 21, 2022
const removeNullAndUndefinedValues = (obj) => {
// create a new object to store the values in
const newObj = {};
// loop over each key/value pair in the passed in object
for (const [key, value] of Object.entries(obj)) {
// if the value is not null or undefined, add it to the new object
if (value !== null && value !== undefined) {
newObj[key] = value;
}
}
// return the new object
return newObj;
};
0
25.550
JavaScript by Radu TM • June 21, 2022
const obj = {
name: '🐶',
age: undefined,
color: 'brown',
weight: undefined
};
// remove all undefined values from obj
Object.keys(obj).forEach(key => obj[key] === undefined && delete obj[key]);
console.log(obj); // { name: '🐶', color: 'brown' }
0
10.804
JavaScript by Radu TM • June 21, 2022
const obj = {
name: 'John',
age: undefined,
gender: 'male'
};
// remove all undefined values from the object
Object.keys(obj).forEach(key => obj[key] === undefined && delete obj[key]);
console.log(obj);
// { name: 'John', gender: 'male' }
0
10.804