Answered
If I have a given object that contains one or more empty strings:
{
username: "Ricky Bobby",
email: "",
password: "",
points: 21
}
How do I remove each key-value pair that contains an empty string for its value?
I'm using JavaScript.
Here's how you could do it:
let myObject = {
username: "Ricky Bobby",
email: "",
password: "",
points: 21
};
Object.keys(myObject).forEach((key) => {
if (myObject[key] === "") {
delete myObject[key];
}
});
// myObject = { username: 'Ricky Bobby', points: 21 }
Code breakdown:
Object.keys(myObject)
creates an array that contains each key in the object. i.e. ["username", "email", "pasword", "points"]
.forEach(keys)
loops through each of those keys and checks the value in the object associated with the key.delete
operator is used to remove that key-value pair.You can iterate over the object using for...in
and delete
any key-value pair with an empty string value:
for (const key in object) {
if (object[key] === "") {
delete obj[key];
}
}
Object.keys(myObject).forEach((key) => {
if (myObject[key] === "") {
delete myObject[key];
}
});
This function will remove each key-value pair that contains an empty string:
const removeEmptyStringValues = (Object) => {
for (var key in Object) {
if (Object[key] === "") {
delete Object[key];
}
}
return Object;
};
You can use it like this:
removeEmptyStringValues(ogObject);