Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing null values in object [duplicate]

I have array of objects like

{
  key1: "value1",
  key2: "value2",
  key3: null,
  key4: "value4",
  ...
}

How can I replace all null values to '-' string (maybe with es6 for shorter code)?

like image 307
bashkovpd Avatar asked Sep 18 '26 02:09

bashkovpd


1 Answers

You can iterate over all keys of an object as follows:

var obj = {a: 1, b:2};
Object.keys(obj).forEach(someFunction);

Now, to replace null-values, you can just test for null and set it to '-'.

var obj = {
  key1: "value1",
  key2: "value2",
  key3: null,
  key4: "value4"
};

Object.keys(obj).forEach(function(key) {
    if(obj[key] === null) {
        obj[key] = '-';
    }
})
like image 168
JanS Avatar answered Sep 19 '26 16:09

JanS