我使用reactJS,并且当我显示我的API调用响应的结果时,我想将每个null值更改为0,以避免错误。我遇到的问题是,每次我想要检查这些值时,都不会显示0。
每次搜索的json数据返回以下内容:
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 { … }如你所见,对象中有对象。我需要“扫描”所有的值,将每个空改为0,并显示它。
下面是问题所在的代码。
//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
}谢谢您的提前付款。
发布于 2020-07-23 08:56:56
我相信你的问题源于这里:
else if(!value){
object.value = 0
}我相信你想要设置object[key] = 0
所以总而言之就是:
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));
https://stackoverflow.com/questions/63045226
复制相似问题