[英]Javascript Check Object for empty or null fields and arrays
我有一個包含很多對象和嵌入式數組的數組。 我需要遍歷整個數組以查看是否為空或null。 我的問題是檢查數組以及數組是否返回空。 我一直在獲取對象數組,它們不是null或未定義,所以即使長度為0也要添加它們。到目前為止,我得到了什么。
var progressCount = 0;
var progressKeyLength = progressBarCriteria.length;
for (var i = 0; i<progressKeyLength; i++){
//I can find the arrays here but still not able to check length since they are actually object arrays.
if(Array.isArray(progressBarCriteria[i])){
console.log('array' + i);
}
if (progressBarCriteria[i] !== null && progressBarCriteria[i] !== ""){
++progressCount
}
}
progressBarCritiria = [
example1: "",
example2: "asdasdas",
example3: 233,
example4: {asda: 1},
example5: {asadasda: "asdasdA"},
example6: "",
example7: [],
example8: [1, 12312],
example9: [{1: "ad"}, {1: 12312}],
]
因此,不應將1、6和7添加到我的計數中。
您可以使用遞歸函數來做到這一點。 重要的是要注意,在javascript數組中是對象。 因此,您需要通過if (typeof arr === 'object' && !(arr instanceof Array))
檢查對象。 有關更多信息,請檢查this和this 。
function recursive_array_chekc (arr) { //check if arr is an object if (typeof arr === 'object' && !(arr instanceof Array)) { //check if object empty if (Object.keys (arr).length === 0) { //do something if empty console.log ('this object is empty'); } else { //check object properties recursivly for (var key in arr) if (arr.hasOwnProperty (key)) recursive_array_chekc (arr[key]) } } else if (Array.isArray (arr)) { //check if array is empty if (arr.length === 0) { //do something if empty console.log ('this array is empty'); } else { //check array elements recursivly for (var i = 0; i < arr.length; i++) recursive_array_chekc (arr[i]) } } }
我能夠看到兩個答案,並提出了這個可行的解決方案。 這是使用Typescript的代碼,很抱歉造成混淆。
for (var i = 0; i<progressKeyLength; i++){
if (!(progressBarCriteria[i] instanceof Array)){
if(progressBarCriteria[i] !== null && progressBarCriteria[i] !== "") {
++progressCount
}
} else {
let current = progressBarCriteria[i];
if (Array.isArray(current) && current.length !== 0){
++progressCount
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.