46

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?

1
  • Wondering if there's an ES6 way to do this Commented Nov 14, 2019 at 22:51

11 Answers 11

51

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);
}
Sign up to request clarification or add additional context in comments.

3 Comments

Please provide a reference for Object.keys. Also, please use correct terminology. "Attributes" is incorrect. Finally, if you're going to get all functional, shouldn't you define the function as setAll = val => obj =>..., and then const setNull = setAll(null);?
This answer still does not set all the values "at once". It loops over the properties.
@torazaburo I ain't saying it's funtional... Just with arrow functions lol (btw it's nearly impossible to set'em 'all at once')
23

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

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

Comments

8

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

Comments

6

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

2 Comments

I thought so, too. But OP didn't want to loop b/c object could be huge. I think @user663031 idea is plausible. Just create a new object.
ESLint throws an error no-prototype-builtins when calling hasOwnProperty directly on an object. One can use Object.prototype.hasOwnProperty.call(obj, key) instead to silence it.
4

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.

Comments

3

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.

Comments

3

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

Comments

3

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

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

Comments

0

you can use for in. Here is an example:

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

Comments

0

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

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.