Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to 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: '-'
}Advertisements