Search code examples
javascriptjavascript-objects

How to replace all nulls with dash in object?


I have an object and for all keys that have a null value I want to replace this null with an empty string (or a dash in my case)?

For example

Obj = {

key1: null,
key2: null,
key3: true,
...
key_n: null

}

Turns into

Obj = {

key1: "-",
key2: "-",
key3: true,
...
key_n: "-"

}

Solution

  • This will work.

    const Obj = {
      key1: null,
      key2: null,
      key3: true,
    
      key_n: null
    };
    
    for (const key in Obj) {
      const val = Obj[key];
    
      if (val === null) {
        Obj[key] = "-";
      }
    }
    console.log(Obj);