[英]Array.every function isn't running on all elements of Object
我正在嘗試使用以下代碼在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將被填充,因為它應該這樣做。 我認為,如果我嘗試搜索狀態 鍵 之后存儲在鍵上的值 ,則會出問題。
您需要在if (typeof value == "object")
內部return Object.values(value).every(valueOfObject....
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)
為什么不考慮使用遞歸檢查對象是否有任何值? 我認為這可以縮短代碼,並且更加直接。
此外, 我 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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.