我有一个对象tableRows数组。
tableRows = [
{
purchase_sales:1000,
yearFirstRemAmount: 1456,
capitalServicePurchase:123234,
otherServicePurchase: 12323,
otherStuffPurchase: 8903,
capitaStuffPurchase: 1200,
currentYearServiceSell: 47856,
currentYearStuffSell: 100000,
yearLastRemAmount: 20000
}
{
purchase_sales:23430,
yearFirstRemAmount: 12500,
capitalServicePurchase: 1000010,
otherServicePurchase: 12360,
otherStuffPurchase: 12300,
capitaStuffPurchase: 12000,
currentYearServiceSell: 123123,
currentYearStuffSell: 12111,
yearLastRemAmount: 13120
}
]如何检查每个索引的9个键对值中是否至少有一个大于或等于100000。
以下代码不起作用:
const handleValidation = (index)=>{
if(tableRows[index].purchase_sales<100000 || tableRows[index].yearFirstRemAmount<100000 || tableRows[index].capitalServicePurchase<100000 || tableRows[index].otherServicePurchase<100000 || tableRows[index].otherStuffPurchase<100000 || tableRows[index].capitaStuffPurchase<100000 || tableRows[index].currentYearServiceSell<100000 || tableRows[index].currentYearStuffSell<100000 || tableRows[index].yearLastRemAmount<100000 ){
alert("'At least one amount should be greater than or equal to 100000!!!")
}
}是否有更好、更简洁的方法来完成这一任务?
发布于 2022-08-07 07:44:39
正如在其他答案中提到的,您可以将对象转换为数组或将其值转换为数组,然后使用some method`‘on数组。
但是,如果您的对象可能有其他键,并且希望检查特定的属性:
const keys = [
'purchase_sales',
'yearFirstRemAmount',
'capitalServicePurchase',
'otherServicePurchase',
'otherStuffPurchase',
'capitaStuffPurchase',
'currentYearServiceSell',
'currentYearStuffSell',
'yearLastRemAmount'
];function validate (obj) {
for (key of keys) {
if(obj[key] >= 100000) {
// Do something here.
// For instance: return true;
}
}
// There is no property with a value greater or equal to 100000.
// Do something here.
// For instance: return false;
} const isValid = tableRows.map(validate).every(Boolean)发布于 2022-08-07 07:30:22
您可以使用map和some的组合
const threshold = 1000000;
const yourAnswer = tableRows.map(Object.values).some(value => value >= threshold);发布于 2022-08-07 07:31:58
const handleValidation = (index)=>{
if (Object.values(tableRows[index]).some(value => value < 100000)) {
alert("'At least one amount should be greater than or equal to 100000!!!")
}
}https://stackoverflow.com/questions/73265622
复制相似问题