'How to set all values of an object to null in 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?



Solution 1:[1]

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);
}

Solution 2:[2]

If you are looking for a short one-liner to copy and paste, use this

Object.keys(obj).forEach((i) => obj[i] = null);

Solution 3:[3]

Another way of doing it, using Array.reduce. It does not overwriting the existing object. This only works if the object only have simple values.

const newObj = Object.keys(originalObj).reduce(
  (accumulator, current) => {
    accumulator[current] = null; 
    return accumulator
  }, {});

Solution 4:[4]

You can use Object.keys() as Nianyi Wang mentioned in his answer, or a for in, like this:

for (key in obj) {
    if (obj.hasOwnProperty(key)) {
        obj[key] = null;
    }
}

But in this case you should check hasOwnProperty().

Solution 5:[5]

But the object can be very big, so I can't just do it one by one.

By "big" do you mean "millions of properties" and you are concerned about performance? Or do you mean "a bunch of properties you don't know the names of, and/or don't want to have list out"?

How to set all properties at once?

You can't. One way or another, you have to loop.

Instead of mutating an existing object, consider creating a new, empty object. Its property values will be undefined, but that could work depending on your code structure.

Solution 6:[6]

Lodash can manage this using cloneDeepWith.

My solution to the same problem:

import * as _ from 'lodash';
const bigObj = {"big": true, "deep": {"nested": {"levels": "many" } } };
const blankObj = _.cloneDeepWith(bigObj, (value) => {return _.isObject(value) ? undefined : null});
console.log(blankObj);
// outputs { big: null, deep: { nested: { levels: null } } }

Returning undefined in the customizer was not obvious to me, but this answer explains that doing so triggers recursion.

Solution 7:[7]

If object contains child object, if you want to set all child object properties to null, recursive solution is below.

function setEmpty(input){

    let keys = Object.keys(input);

        for( let key of keys ){

             if(typeof input[key] != "object" ){
                 input[key] = null;
             }else{
                 setEmpty(input[key]);
             }
        }
        return input;
    }

Solution 8:[8]

you can use for in. Here is an example:

let obj = {prob1:"value1", prob2:"value2"}
for(let prob in obj){obj[prob]=null} 

Solution 9:[9]

export const setObjToNull = (obj) => {
    var returnObj = {};
    Object.keys(obj).map((key) => {
        let nullObj = { [key]: '' };
        Object.assign(returnObj, nullObj);
    })
    return returnObj;
}

Solution 10:[10]

let values = {
    a:1, 
    b:'', 
    c: {
        a:'', 
        s:4, 
        d: {
            q: '',
            w: 8,
            e: 9
        }
 
    }
}


values;

const completeWithNull = (current) => {
  Object.keys(current).forEach((key) => {
   		current[key] = current[key] === ''? null 
    	: typeof current[key] === 'object' ? completeWithNull(current[key])
    	: current[key]
  });
  
  return current;
};

completeWithNull(values);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Caio Ladislau
Solution 2 Aryeh Beitz
Solution 3 Xun Yang
Solution 4 Maksim Kalmykov
Solution 5
Solution 6 MM.
Solution 7 Community
Solution 8
Solution 9 Hemant Kumar
Solution 10 Bruno Souza