How to Replace null with “-” JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

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: '-'
}
raja
Published on 21-Aug-2020 18:26:11
Advertisements