Home > Enterprise >  How to replace all nulls with dash in object?
How to replace all nulls with dash in object?

Time:04-29

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: "-"

}

CodePudding user response:

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);

CodePudding user response:

You just have to match whether a key's corresponding value is null or not , if yes then change it to underscore.

Obj = {

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

    }

    Object.keys(Obj).map(key=>{
        if(!Obj[key])Obj[key] = "_"
    })
    console.log(Obj)

  • Related