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?
-
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
3 Answers
Reset to default 4fastest 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
版权声明:本文标题:dictionary - Set Javascript object values to null - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745198706a2647266.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论