Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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...

like image 503
Akanksha Iyer Avatar asked Nov 29 '25 03:11

Akanksha Iyer


2 Answers

Here's something quick:

var results = [{
    id: null,
    name: "Rick",
    Value: "34343"
}, {
    id: 2,
    name: null,
    Value: "2332"
}, {
    id: 2,
    name: 'mike',
    Value: null
}];

results.forEach(function(object){
    for(key in object) {
        if(object[key] == null)
            object[key] = '';
    }
});

console.log(JSON.stringify(results, null, 2))
like image 155
Jeremy Jackson Avatar answered Dec 01 '25 15:12

Jeremy Jackson


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 (const obj of arr) {
  if (typeof obj !=== 'object') continue;
  for (k in obj) {
    if (!obj.hasOwnProperty(k)) continue;
    v = obj[k];
    if (v === null || v === undefined) {
      obj[k] = '';
    }
  }
}

If your keys are known:

for (const obj of arr) {
  if (obj.name === undefined || obj.name === null) {
    obj.name = '';
  }
}
like image 39
casraf Avatar answered Dec 01 '25 17:12

casraf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!