Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set all values of an object to null in JavaScript?

Tags:

javascript

I need to set all properties of some object to null. But the object can be very big, so I can't just do it one by one.

How to set all properties at once?

like image 232
Pilgrim Avatar asked Aug 26 '17 17:08

Pilgrim


People also ask

How do you null an object in JavaScript?

Javascript null is a primitive type that has one value null. JavaScript uses the null value to represent a missing object. Use the strict equality operator ( === ) to check if a value is null . The typeof null returns 'object' , which is historical bug in JavaScript that may never be fixed.

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.

Is null and 0 the same JavaScript?

Strange result: null vs 0 Comparisons convert null to a number, treating it as 0 . That's why (3) null >= 0 is true and (1) null > 0 is false. On the other hand, the equality check == for undefined and null is defined such that, without any conversions, they equal each other and don't equal anything else.

How do you assign a null in Java?

In Java, a null value can be assigned to an object reference of any type to indicate that it points to nothing. The compiler assigns null to any uninitialized static and instance members of reference type. In the absence of a constructor, the getArticles() and getName() methods will return a null reference.


1 Answers

Here's a useful function called 'Object.keys()', it returns all of the attribute names of an object.

let setAll = (obj, val) => Object.keys(obj).forEach(k => obj[k] = val); let setNull = obj => setAll(obj, null); 

Non-arrow-function version:

function setAll(obj, val) {     /* Duplicated with @Maksim Kalmykov         for(index in obj) if(obj.hasOwnProperty(index))             obj[index] = val;     */     Object.keys(obj).forEach(function(index) {         obj[index] = val     }); } function setNull(obj) {     setAll(obj, null); } 
like image 160
Nianyi Wang Avatar answered Oct 06 '22 17:10

Nianyi Wang