0

I have a object

var data = {1:undefined,2:null,3:10,4:""}

I want to replace all the undefined and null values by 0. I am using the following code to do that:

for (var index in data) {
    if (!data[index]) {
        data[index] = 0;
    }
}

Result I am expecting is : {1:0,2:0,3:10:4:""} But Result is : {1:0,2:0,3:10:4:0} because it is considering empty string as null. Is it known behavior ?

I can check it by using (if(data[index] == undefined || data[index] == null)) But I wanted to know the behavior of the above solution.

Bhuneshwer
  • 577
  • 1
  • 9
  • 26

3 Answers3

1

You can add typeof data[index] != 'string'

var data = {1:undefined,2:null,3:10,4:""}

for (var index in data) {
  if (!data[index] && typeof data[index] != 'string') {
    data[index] = 0;
  }
}

console.log(data)
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
1

This is because a string of length 0 is "falsy", which means that it, if evaluated as a boolean, will translate to false. Read more on "falsy" over here. You can fix your code in the following way:

for (var index in data) {
    if (typeof data[index] == "undefined" || data[index] == null) {
        data[index] = 0;
    }
}
0

Try:

if ((typeof <your variable> == "undefined") ||
    (       <your variable> == ""         )    ) {
    <your variable> = 0 ;
}

By the way, Are you using "1", "2" indices?

FDavidov
  • 3,505
  • 6
  • 23
  • 59