admin管理员组

文章数量:1415684

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?

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?

Share Improve this question edited Jul 6, 2020 at 8:24 tomerpacific 6,61318 gold badges41 silver badges60 bronze badges asked Jul 6, 2020 at 7:14 HackleSawHackleSaw 1393 silver badges16 bronze badges 3
  • 1 Object.prototype.keys() + Array.prototype.forEach() – Andreas Commented Jul 6, 2020 at 7:17
  • Yes it loops through the properties of the object and sets them to null. – Mick 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. – HackleSaw Commented Jul 6, 2020 at 7:40
Add a ment  | 

3 Answers 3

Reset to default 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.

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

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

本文标签: dictionarySet Javascript object values to nullStack Overflow