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 Answers
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.
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;
}
Object.prototype.keys()
+Array.prototype.forEach()