3

I am trying to rewrite null values in an object to zeros.

var data = {
    a : 1,
    b: 22,
    c: null,
    d: 1
};

for(var i=0; i < data.length; i++) {
    if (data[i].value === null){
        data[i].value = 0;
    }

}

What I am missing here?

user2917823
  • 199
  • 1
  • 9
  • 2
    data.length will be undefined as there is no length property. Loop like this: [How do I loop through or enumerate a JavaScript object?](http://stackoverflow.com/questions/684672/how-do-i-loop-through-or-enumerate-a-javascript-object) – Alex K. Apr 03 '17 at 18:18

2 Answers2

5

You are using wrong loop and treating object like an array. Use for-in loop

The for...in statement iterates over the enumerable properties of an object, in arbitrary order. For each distinct property, statements can be executed.

var data = {
  a: 1,
  b: 22,
  c: null,
  d: 1
};

for (var i in data) {
  if (data[i] === null) {
    data[i] = 0;
  }
}
console.log(data)
Satpal
  • 132,252
  • 13
  • 159
  • 168
1

Since the data variable is an object, the length property won't work on it. You could use Array#reduce together with Object.keys to achieve the desired result.

var data = { a: 1, b: 22, c: null, d: 1 };

data = Object.keys(data).reduce(function(s,a) {
  data[a] == null ? s[a] = 0 : s[a] = data[a];
  return s;
}, {});

console.log(data);
kind user
  • 40,029
  • 7
  • 67
  • 77