Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Replace Null with JavaScript



We have to write a function that takes in an object with many keys and replaces all false values with a dash (‘ - ’). We will simply iterate over the original object, checking for the keys that contain false values, and we will replace those false values with ‘-’ without consuming any extra space (i.e., in place)

Example

const obj = {
   key1: 'Hello',
   key2: 'World',
   key3: '',
   key4: 45,
   key5: 'can i use arrays',
   key6: null,
   key7: 'fast n furious',
   key8: undefined,
   key9: '',
   key10: NaN,
};
const swapValue = (obj) => {
   Object.keys(obj).forEach(key => {
      if(!obj[key]){
         obj[key] = '-';
      }
   });
};
swapValue(obj);
console.log(obj);

Output

The output in the console will be −

{
   key1: 'Hello',
   key2: 'World',
   key3: '-',
   key4: 45,
   key5: 'can i use arrays',
   key6: '-',
   key7: 'fast n furious',
   key8: '-',
   key9: '-',
   key10: '-'
}
Updated on: 2020-08-21T14:56:26+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements