我正在尝试使用以下代码在temp1
内部进行搜索,如果任何值具有字符串"processado"
let temp1 = [{
"id":7089,
"value":"R$ 50,00",
"name":"Daiany Nascimento",
"date":"18/03/2019",
"type":"Cobrança",
"status":{
"status":"Paga",
"icon":"paid"
},
"credit_release_date":"Não Processado",
"credit_release_description":"— — — —"
}]
let b = []
temp1.forEach((a,index_a) => {
Object.values(a).every((value,index,array) => {
let expression = new RegExp("processado", "i") //expression to search
if (typeof value == "object") {
Object.values(value).every(valueOfObject => {
if (expression.test(valueOfObject)) {
b.push(temp1[index_a])
return false;
} else {
return true
}
})
}
else if (expression.test(value)){
b.push(temp1[index_a])
return false
}
else {
return true
}
})
})
但是,数组b 保持为空。如果我尝试搜索字符串"Cobrança"
,则会按需填充数组b 。我认为,如果我尝试搜索状态键之后后存储在键 上的值,会出错
答案 0 :(得分:2)
您需要在return Object.values(value).every(valueOfObject....
内if (typeof value == "object")
let temp1 = [{"id":7089,"value":"R$ 50,00","name":"Daiany Nascimento","date":"18/03/2019","type":"Cobrança","status":{"status":"Paga","icon":"paid"},"credit_release_date":"Não Processado","credit_release_description":"— — — —"}]
let b = []
temp1.forEach((a,index_a) => {
Object.values(a).every((value,index,array) => {
let expression = new RegExp("processado", "i") //expression to search
if (typeof value == "object") {
return Object.values(value).every(valueOfObject => {
if (expression.test(valueOfObject)) {
b.push(temp1[index_a])
return false;
} else {
return true
}
})
}
else if (expression.test(value)){
b.push(temp1[index_a])
return false
}
else {
return true
}
})
})
console.log(b)
一种更简单,更简洁的方法是使用递归以及filter()
和some()
。 every()
在这里对我没有任何意义
let temp1 = [{"id":7089,"value":"R$ 50,00","name":"Daiany Nascimento","date":"18/03/2019","type":"Cobrança","status":{"status":"Paga","icon":"paid"},"credit_release_date":"Não Processado","credit_release_description":"— — — —"}]
function check(obj,regex){
return Object.values(obj).some(x =>{
let y;
if(typeof x === "object") y = check(x,regex);
return y || regex.test(x);
});
}
let b = temp1.filter(x => check(x,/Processado/i))
console.log(b)
答案 1 :(得分:1)
为什么不考虑使用递归检查对象是否有任何值?我认为这样做可以缩短代码,并使代码更简单。
此外,对我来说 Array.prototype.some
在这种情况下比Array.prototype.every
更有意义(除非我遗漏了一些东西):
const temp1 = [{
"id": 7089,
"value": "R$ 50,00",
"name": "Daiany Nascimento",
"date": "18/03/2019",
"type": "Cobrança",
"status": {
"status":"Paga",
"icon":"paid"
},
"credit_release_date": "Não Processado",
"credit_release_description": "— — — —"
}];
const b = [];
const expression = new RegExp('processado', 'i');
const hasExpr = obj => Object.values(obj).some((value, i) => {
if (typeof value === 'object')
return hasExpr(value);
return expression.test(value);
});
temp1.forEach(item => {
if (hasExpr(item))
b.push(item);
});
console.log(b);