Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set all object properties to null in JavaScript?

I am using Vue and suddenly some of the computed css using vuetify is not working.

The way I declare an object is

personal_info : {}

and in my template, I could just do personal_info.name and other more in every v-model of text input.

I have no errors but suddenly the vuetify has a class called input-group--dirty that will elevate the label of the text input whenever it's not empty. But suddenly, it's not working. It looks like this:

enter image description here

As you can see, the text and label are overlapping.
The only thing that make it work is to set the property to null which is:

personal_info : {
  name: null
}

The problem is that I have hundreds of text inputs and I dont want to set everything to null.

Is there a simple way to set all of the object's properties to null instead of coding it 1 by 1?

like image 257
wobsoriano Avatar asked Feb 22 '17 07:02

wobsoriano


People also ask

How do you null an object in JavaScript?

The value null represents the intentional absence of any object value. It is one of JavaScript's primitive values and is treated as falsy for boolean operations.

Can we assign null to object in JavaScript?

In order to set object values to null, you need to get all the keys from the object and need to set null. You can use for loop or forEach() loop.

Can I set an object to null?

An object of a class cannot be set to NULL; however, you can set a pointer (which contains a memory address of an object) to NULL.

Does null have properties in JavaScript?

The trap of null null might appear, often unexpectedly, in situations when you expect an object. Then if you try to extract a property from null , JavaScript throws an error. Because who variable is an empty string, the function returns null . When accessing message property from null , a TypeError error is thrown.


2 Answers

checkout this snippet

var personal_info = {
  name: 'john',
  email: '[email protected]',
  phone: 9876543210
}
console.log(JSON.stringify(personal_info)); //before looping

for (var key in personal_info ) {
  personal_info[key] = null;
}

console.log(JSON.stringify(personal_info));//after looping and setting value to 'null'
like image 117
Vilas Kumkar Avatar answered Sep 19 '22 13:09

Vilas Kumkar


Vilas example is ok. But in case you have nested properties and your obj looks like this you could try my snippet

var obj = {
  a: 1 ,
  b: 2,
  c: {
    e:3,
    b: {
      d:6,
      e: ['23']
    }
  }
};

var setProps = function(flat, newVal){
   for(var i in flat){
     if((typeof flat[i] === "object") && !(flat[i] instanceof Array)){
       setProps(flat[i], newVal);
       return;
     } else {
       flat[i] = newVal;
     }
  }
}
setProps(obj, null);

console.log(JSON.stringify(obj));
like image 32
Cassidy Avatar answered Sep 21 '22 13:09

Cassidy