TransWikia.com

Change null to 0 in response

Stack Overflow Asked by Edwin Landsfield on December 3, 2021

I use reactJS and I would like to change each null value to 0 when I display the results of my API call responses and avoid errors. the problem I am having is that every time I want to check the values, the display of 0 does not occur.

The json data from each search returns this:

cases: Object { new: "+14", active: 233, critical: 6, … }
continent: "Asia"
country: "China"
day: "2020-07-23"
deaths: Object { new: null, 1M_pop: "3", total: 4634 }
population: 1439323776
tests: Object { 1M_pop: "62814", total: 90410000 }
time: "2020-07-23T00:45:06+00:00"
<prototype>: Object { … }

As you see there is objects in the object. I need to "scan" all value to changing each null to 0 and display it.

Here my code where the problem is.

//replace Null value to 0
function isNull(object) {
   for (const [key, value] of Object.entries(object)) {
       if (typeof(value) === "object" && value !== null) {
           isNull(value)
       }else if(!value){
          object.value = 0
         }
       }
         return object
   }

thanks by advance.

One Answer

I believe your issue stems from here:

else if(!value){
  object.value = 0
}

I believe you want to set the object[key] = 0

So altogether it'd be:

else if(!value){
  object[key] = 0
}

const response = {
  cases: { new: "+14", active: 233, critical: 6 },
  continent: "Asia",
  country: "China",
  day: "2020-07-23",
  deaths: { new: null, "1M_pop": "3", total: 4634 },
  population: 1439323776,
  tests: { "1M_pop": "62814", total: 90410000 },
  time: "2020-07-23T00:45:06+00:00"
 };

function isNull(object) {
    for (const [key, value] of Object.entries(object)) {
        if (typeof(value) === "object" && value !== null) {
            isNull(value)
        }else if(!value){
            object[key] = 0
        }
    }
    return object
}
console.log(isNull(response));

Answered by Spencer Bard on December 3, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP