How to Replace Null Value with 0 from an Array in Javascript?

Sep 23, 2022 . Admin



Hello dev,

This article is focused on how to replace null value with 0 from an array javascript. This article will give you simple example of how to replace null with 0 in array using javascript. you can understand a concept of replace null value with 0 from an array in javascript. if you have question about javascript replace null value with 0 from an array then I will give simple example with solution.

In this example, I am going to explain to you how to replace a null value with 0 from an array in javascript. We have to write a function that takes in an object with many keys and replaces all false values with a (0). We will simply iterate over the original object.

So, let's see bellow solution:

Example: 1
index.html
<!DOCTYPE html>
<html>
    <head>
        <title>How to Replace Null Value with 0 from an Array  in Javascript? - MyWebtuts.com</title>
    </head>
    <body>
        <h1>How to Replace Null Value with 0 from an Array  in Javascript? -  MyWebtuts.com</h1>
        
        <script type="text/javascript">
            const obj = {
                key1: 'Hello',
                key2: 'Pratik',
                key3: 45,
                key4: null,
            };
            const swapValue = (obj) => {
                Object.keys(obj).forEach(key => {
                    if(!obj[key]){
                        obj[key] = 0;
                    }
                });
            };
            swapValue(obj);

            //Give output to console...
            console.log(obj);
        </script>
    </body>
</html>
Output:
{
   key1: "Hello",
   key2: "Pratik",
   key3: 45,
   key4: 0
}
I hope it will help you...
#Javascript