使用 JavaScript 将对象中的所有值设置为 Null
要将对象中的所有值设置为空,请将该对象传递给 Object.keys()
方法以获取对象键的数组,然后使用 forEach()
方法遍历该数组,将每个值设置为空。 在最后一次迭代之后,该对象将只包含空值。
const obj = {
name: 'Tom',
age: 30,
country: 'Chile',
};
Object.keys(obj).forEach(key => {
obj[key] = null;
});
// 👇️ {name: null, age: null, country: null}
console.log(obj);
我们使用 Object.keys
方法获取对象键的数组。
const obj = {
name: 'Tom',
age: 30,
country: 'Chile',
};
// 👇️ ['name', 'age', 'country']
console.log(Object.keys(obj));
下一步是使用 Array.forEach
方法迭代数组。
我们传递给
forEach
方法的函数会针对数组中的每个元素进行调用。
在每次迭代中,我们将当前键的值设置为 null。
在最后一次迭代之后,对象中的所有值都将设置为 null。
另一种方法是不改变对象,而是使用 Array.reduce
方法创建一个新对象。
使用 reduce() 将对象中的所有值设置为 Null
要将对象中的所有值设置为 null,请将对象传递给 Object.keys()
方法以获取对象键的数组并使用 reduce()
方法迭代该数组。 在每次迭代中,扩展累加器对象,将键设置为 null 值并返回结果。
const obj = {
name: 'Tom',
age: 30,
country: 'Chile',
};
const newObj = Object.keys(obj).reduce((accumulator, key) => {
return {...accumulator, [key]: null};
}, {});
// 👇️ {name: null, age: null, country: null}
console.log(newObj);
我们传递给 reduce
方法的函数会为 keys 数组中的每个元素调用。
我们将累加器变量的初始值设置为一个空对象。
在每次迭代中,我们使用扩展语法
...
将累积对象的键值对解包到一个新对象中,将当前属性设置为null
。
选择哪种方法取决于个人喜好。 我更喜欢在这种情况下使用 forEach,因为我觉得它更直接。 如果不想改变原始对象,请使用 reduce
方法。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
比较 Pandas DataFrame 对象
发布时间:2024/04/21 浏览次数:79 分类:Python
-
本教程介绍了我们如何在 Python 中比较 Pandas DataFrame 对象。比较 DataFrames 对检查 DataFrames 之间的差异非常有帮助。
如何在 JavaScript 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。