I'm trying to search inside temp1
if any value has the string "processado"
using the following code
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
}
})
})
But, the array b remains empty. If I try to search the string "Cobrança"
, the array b get filled, as it should. I think that if I try to search values that are stored on keys after the status key, something get wrong.
You need to return Object.values(value).every(valueOfObject....
inside 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)
A simpler and cleaner way is using recursion and filter()
and some()
. every()
doesnot make any sense to me here
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)