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
  • 1
    Object.prototype.keys() + Array.prototype.forEach() Commented Jul 6, 2020 at 7:17
  • Yes it loops through the properties of the object and sets them to null. Commented Jul 6, 2020 at 7:19
  • @Mick I've tried using it. It does loop over them but isn't setting them to null. Commented Jul 6, 2020 at 7:40

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

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.