How to automate this object using JavaScript to set one key on each iteration as null?



For this, use Object.keys() and set one key on each iteration as null using a for loop..

Example

Following is the code −

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

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo294.js.

Output

This will produce the following output on console −

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 }

Advertisements