Pilgrim
Pilgrim

Reputation: 573

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?

Upvotes: 46

Views: 61837

Answers (11)

Nimish Gupta
Nimish Gupta

Reputation: 1051

You can use Object.fromEntries & Object.entries like this

Object.fromEntries(
  Object.keys(obj).map((key) => [key, null])
)

Upvotes: 3

Hemant Kumar
Hemant Kumar

Reputation: 1

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

Upvotes: 0

Ali Mamedov
Ali Mamedov

Reputation: 139

you can use for in. Here is an example:

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

Upvotes: 0

Malaji Nagaraju
Malaji Nagaraju

Reputation: 151

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

Upvotes: 3

Aryeh Beitz
Aryeh Beitz

Reputation: 2078

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

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

Upvotes: 23

MM.
MM.

Reputation: 2036

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.

Upvotes: 3

Bruno Souza
Bruno Souza

Reputation: 29

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

Upvotes: -1

Nianyi Wang
Nianyi Wang

Reputation: 773

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

Upvotes: 51

Xun Yang
Xun Yang

Reputation: 4419

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

Upvotes: 8

user663031
user663031

Reputation:

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.

Upvotes: 4

Maksim Kalmykov
Maksim Kalmykov

Reputation: 1317

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().

Upvotes: 6

Related Questions