kbw24110
kbw24110

Reputation: 11

how to nullify object values in javascript

Lets assume I have object such as;

var obj = {
    name: "alex",
    surname: "black",
    age: 21,
    grade: 14
}

I want to nullify all values as;

var obj = {
    name: "",
    surname: "",
    age: 0, 
    grade: 0
}

How can I do this? I can look through keys by Object.keys(obj) and nullify each key according to their type.

Like;

var str ="";
for(var i =0; i < obj.length; i++){
   if(type of obj[i] === "string")
      str += Object.keys(obj)[i] + ': "",\n';
   if(type of obj[i] === "integer")
      str += Object.keys(obj)[i] + ': 0,\n';

}

Is it the proper way to do it?

edit: Thank you for your all answers. But this object can also contain objects. So I should loop through all the keys and nullify them as your example shows. Am I right?

Upvotes: 1

Views: 4567

Answers (3)

deceze
deceze

Reputation: 522110

Use a for..in loop to iterate the object properties:

for (var prop in obj) {
    if (obj.hasOwnProperty(prop)) {
        obj[prop] = { string: '', number: 0 }[typeof obj[prop]];
    }
}

Alternatively maybe a switch inside the loop:

switch (typeof obj[prop]) {
    case 'string':
        obj[prop] = '';
        break;

    case 'number':
        obj[prop] = 0;
        break;

    default:
        obj[prop] = null;
}

Upvotes: 4

Scott Marcus
Scott Marcus

Reputation: 65806

Like either of these:

for/in (used to iterate ALL properties of an object) or

Object.keys(obj).forEach(f) (gets array of an object's OWN properties and loops them)

var obj = {
    name: "alex",
    surname: "black",
    age: 21,
    grade: 14,
    someObject: {dob: "12/16/66", address: "10 Main Street"}
}

var obj2 = {
    name: "alex",
    surname: "black",
    age: 21,
    grade: 14,
    someObject: {dob: "12/16/66", address: "10 Main Street"}
}

// Using for/in
function reset(obj){
  for(var k in obj){
   switch(typeof obj[k]){
       case "string":
          obj[k]="";
          break;
       case "number":
          obj[k]= 0;
          break;
       case "boolean":
          obj[k]= false;
          break;
       case "object":
          obj[k]= null;
          break;       
   }
  }
}

// Using Object.keys()
function reset2(obj){
  Object.keys(obj).forEach(function(k){
   switch(typeof obj2[k]){
       case "string":
          obj[k]="";
          break;
       case "number":
          obj[k]= 0;
          break;
       case "boolean":
          obj[k]= false;
          break;
       case "object":
          obj[k]= null;
          break;       
   }
  });
}

reset(obj);
console.log(obj);

reset2(obj2);
console.log(obj2);

Upvotes: 0

anshuVersatile
anshuVersatile

Reputation: 2068

Object.keys(obj).forEach(function(key) {
    console.log(key, obj[key]);
    if(type of obj[key] === "string")
      // do something
    if(type of obj[key] === "integer")
      // do something

});

Upvotes: 0

Related Questions