13

Let's say I have the following JS Object

data = {
    name: "John",
    dataOfBirth: "",
    externalId: 2548,
    email: "john@email.com",
    mobile: ""
}

I will receive an object like this with many more properties that can be either String, Integer or undefined. For me to update my database, I cannot override a valid information with an empty one.

I could try if (data.email === "") delete data.email with all of them, but that seems unpractical to maintain.

Is there any way I can scan all properties without having to name every single one of them and remove all empty/undefined ones?

Caio Favero
  • 2,196
  • 3
  • 17
  • 18

2 Answers2

11

You could simply loop through the object keys and check for each element if they value is blank.

var data = {
        name: "John",
        dataOfBirth: "",
        externalId: 2548,
        email: "john@email.com",
        mobile: ""
    }

    for(var key in data) {
        if(data[key] === "") {
           console.log(key + " is blank. Deleting it");
           delete data[key]
        }
    }
basic
  • 3,348
  • 3
  • 21
  • 36
9

Can't you do this? Or am I missing something?

Object.entries(data).filter(([k,v],i)=>!!v)

give you this:

"[
    [
        "name",
        "John"
    ],
    [
        "externalId",
        2548
    ],
    [
        "email",
        "john@email.com"
    ]
]"

!! will turn a value into boolean, at that stage you filter out null,NaN and undefined. Indeed, if you want to try this on nested objects, then you have to recursively do this because !!Object() is always true. Even better would be to recursively and asynchronously copy the object, filter out falsey primitives and pass a callback to stringify in the end.

Edit:

Someone below mentioned some falsey values that you might want to keep such as 0. In that case chain them:

v===null || v===0 || !!v //null, 0 and anything not falsey, but not undefined etc.
ibrahim tanyalcin
  • 5,643
  • 3
  • 16
  • 22
  • While this code may answer the question, providing additional context regarding _how_ and/or _why_ it solves the problem would improve the answer's long-term value. – Andreas Aug 03 '18 at 19:49
  • For me it's a quick hack to get rid of NaN,null,undefined etc.But if he want's to do this on deeply nested Object, then he needs to deep clone and iterate on this. The true answer would have to dig much deeper. If you think you can add some value, you are more then welcome to edit Andreas, thank you. – ibrahim tanyalcin Aug 03 '18 at 19:50
  • What if the value is 0, or some other falsy value that actually makes sense. – Salman A Aug 03 '18 at 19:54
  • try to think of all these edge cases, for 0,you can do v===0 || !!v. You can extend and chain – ibrahim tanyalcin Aug 03 '18 at 19:59