JavaScript by Radu TM • June 21, 2022
const obj = {
name: '',
email: '[email protected]',
phone: '',
};
// we can use Object.keys(obj) to get an array of the object's keys
// then, we can use the .filter() method to remove any keys whose values are empty strings
const newObj = Object.keys(obj)
.filter(key => obj[key] !== '')
.reduce((acc, key) => {
// finally, we can use .reduce() to turn our array of keys back into an object
acc[key] = obj[key];
return acc;
}, {});
console.log(newObj);
// { email: '[email protected]' }
0
25.345
JavaScript by Radu TM • June 21, 2022
const obj = {
name: '',
age: 0,
address: '',
};
// using for..in loop
for (const key in obj) {
// check if the property is an empty string
if (obj[key] === '') {
// delete the property
delete obj[key];
}
}
// Output: { age: 0 }
console.log(obj);
0
25.345