1

I'm fairly new to js. Is there a way to set all the values of keys (fields) in a JS object to null? Without doing it manually one by one? Because the object is large. I've tried using Object.values(obj) == null but it doesn't work. I've read the answer here, but I can't understand how is it setting the values to null. I think it's just looping over them. Am I wrong?

3

3 Answers 3

4

fastest and most readable way in my opinion:

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

Object.keys retrieve all the keys from a given object, and then just iterate through to set them to null.

2
for (const field in object) object[field] = null
1

Do not mutate the original object, make a copy, return and use it.

createEmptyValues(obj){ 
  let copyObj = {...obj};
  for (const [key, value] of Object.entries(copyObj)) {
    if(Array.isArray(copyObj[key])){
      // if set array to empty then use copyObj[key] = [];
      // if set individual keys of your array to empty, do below
      for (let index = 0; index < copyObj[key].length; index++) {
        copyObj[key][index] = this.createEmptyValues(copyObj[key][index]); 
      }
    } else {
      switch(typeof value){
        case 'string':
        copyObj[key] = '';
        break;
        case 'number':
        copyObj[key] = '';
        break;
        case 'boolean':
        copyObj[key] = false;
        break;
        case 'object':
        if(value !== null){
          copyObj[key] = this.createEmptyValues(value);
        }
        break;
      }
    }
  }
  return copyObj;
}

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.