如何使用 JavaScript 自动执行此对象以将每次迭代中的一个键设置为 null?

javascriptweb developmentfront end technologyobject oriented programming更新于 2026/2/14 17:48:17

为此,使用 Object.keys() 并使用 for 循环将每次迭代中的一个键设置为 null。

示例

以下是代码 −

var objectValues =
{
   "name1": "John",
   "name2": "David",
   "address1": "US",
   "address2": "UK"
}
for (var tempKey of Object.keys(objectValues)) {
   var inEachIterationSetOneFieldValueWithNull = {
      ...objectValues,
       [tempKey]: null
   };
   console.log(inEachIterationSetOneFieldValueWithNull);
}

要运行上述程序,您需要使用以下命令 −

node fileName.js.

这里,文件名是 demo294.js。

输出

这将在控制台上产生以下输出 −

PS C:\Users\Amit\javascript-code> node demo294.js
{ name1: null, name2: 'David', address1: 'US', address2: 'UK' }
{ name1: 'John', name2: null, address1: 'US', address2: 'UK' }
{ name1: 'John', name2: 'David', address1: null, address2: 'UK' }
{ name1: 'John', name2: 'David', address1: 'US', address2: null }

相关文章


有用资源