2

I have following JavaScript object

myObject = {
    Fname: 'A',
    Mname: null,
    Lname: 'C',
    Email: 'AB@gmail.com',
    Address: null,
    Login: 'AB',
    Active: null
};

I want to set fields to some default value if it null so my resulting object should be like.

Object {
    Fname: "A",
    Mname: "",
    Lname: "C",
    Email: "AB@gmail.com",
    Address: "",
    Login: 'AB',
    Active: ""
}

Is there any fast way for doing that because in my case there are about 80 to 100 fields of object. And it takes too much time to check the fields one by one

Tushar
  • 85,780
  • 21
  • 159
  • 179
Muzafar Khan
  • 826
  • 3
  • 15
  • 28

1 Answers1

3

You can use Object.keys and forEach as follow.

myObject = {
  Fname: 'A',
  Mname: null,
  Lname: 'C',
  Email: 'AB@gmail.com',
  Address: null,
  Login: 'AB',
  Active: null
};

// Get array of keys of the object
// Loop over it
Object.keys(myObject).forEach(function(e) {

  // If value of the object member is `null` set it to `''` - empty string.
  if (myObject[e] === null)
    myObject[e] = '';
});

console.log(myObject);
document.write('<pre>' + JSON.stringify(myObject, 0, 2) + '</pre>');

You can also use regex with JSON.parse and JSON.stringify

myObject = JSON.parse(JSON.stringify(myObject).replace(/:null/g, ':""'));

var myObject = {
  Fname: 'A',
  Mname: null,
  Lname: 'C',
  Email: 'AB@gmail.com',
  Address: null,
  Login: 'AB',
  Active: null
};

myObject = JSON.parse(JSON.stringify(myObject).replace(/:null/g, ':""'));

console.log(myObject);
document.write('<pre>' + JSON.stringify(myObject, 0, 2) + '</pre>');
Tushar
  • 85,780
  • 21
  • 159
  • 179
  • 2
    I personally would prefer if (myObject[e] === null) { myObject[e] = "" } so you're not doing pointless assignment operators. – ryanlutgen Oct 07 '15 at 04:24