Akanksha Iyer Akanksha Iyer - 3 months ago 7
Javascript Question

Change all null to '' in array of Objects (javascript)

I have this array of objects shown below

Object {Results:Array[3]}
Results:Array[3]
[0-2]
0:Object
id=null
name: "Rick"
Value: "34343"
1:Object
id=2
name: null
Value: "2332"
2:Object
id=2
name:'mike'
Value: null


As you can see, in 1 object i have id as null, 2nd object has name as null and 3rd object has Value as null. Each object has some property as null.

I want to loop through all of these and replace null with ''. Can someone let me know how to achieve this...

Answer

You only needed to Google looping through objects. Here's an example:

Looping through every key (if your keys are unknown or you want to do the same for all keys)

for (var i=0; i<arr.length; i++) {
  var obj = arr[i];
  if (typeof obj === 'object') {
    for (k in obj) {
      v = obj[k];
      if (v === null || v === undefined) {
        obj[k] = '';
      }
    }
  }
}

If your keys are known:

for (var i=0; i<arr.length; i++) {
  var obj = arr[i];
  if (obj.name === undefined || obj.name === null) {
    obj.name = '';
  }
}