Remove each object property with an empty string value using JavaScript?

Answered
coderguy asked this question 5 months ago
coderguy on Mar 13 · Edited

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.

4 suggested answers
yaboy01 on Mar 13 · Edited

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.
  • If the key contains an empty string, the delete operator is used to remove that key-value pair.
0 replies
nick on Mar 13

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];
  }
}
0 replies
timmy123 on Mar 13 · Edited
Object.keys(myObject).forEach((key) => {
    if (myObject[key] === "") {
        delete myObject[key];
    }
});
0 replies
itsbambi on Mar 13

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);
0 replies
Answered