我有一个如下所示的 JSON 对象
var allUsers = {
"student_a":{
id:1,
full_name:"ABC",
address:"xyz",
image:"image url"
},
"student_b":{
id:2,
full_name:"DEF",
address:"",
image:"image url"
},
"student_c":{
id:3,
full_name:"",
address:"",
image:""
}
}
在上面的 JSON 中,我需要计算出每个学生中有多少个空字段。
我正在使用下面的代码
_submitInfo(allUsers) {
var empty_fields = Object.entries(allUsers).map(([key, value]) => {
return this._validateStudent(value)
})
alert(JSON.stringify(empty_fields))
}
_validateStudent(studentInfo) {
empty = 0;
Object.entries(studentInfo).map(([key, value]) => {
if (value == "") {
empty++
}
})
return empty
}
但我得到的输出是 [0,0,0]
所需的输出是 [0,1,3]
。
我认为 promises 会解决这个问题,但我不知道我将如何在这种嵌套情况下使用它们。
最佳答案
由于您想使用 promises 解决上述问题,我用 promises 更新了您的代码,请看一下。
var allUsers = {
"student_a": {
id: 1,
full_name: "ABC",
address: "xyz",
image: "image url"
},
"student_b": {
id: 2,
full_name: "DEF",
address: "",
image: "image url"
},
"student_c": {
id: 3,
full_name: "",
address: "",
image: ""
}
}
check(allUsers);
function check() {
const promiseContainer = [];
Object.entries(allUsers).map(([key, value]) => {
promiseContainer.push(_validateStudent(value));
});
function _validateStudent(studentInfo) {
let empty = 0;
return new Promise((resolve, reject) => {
Object.entries(studentInfo).map(([key, value]) => {
if (value == "") {
empty++
}
})
resolve(empty);
});
}
Promise.all(promiseContainer).then((count) => { console.log(count) });
}
关于javascript - 用 promise react native 嵌套对象循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54141760/