检查对象中的值是否为null或空javascript
这就是我的问题:我可以拥有这个对象数组:检查对象中的值是否为null或空javascript,javascript,jquery,angularjs,forms,Javascript,Jquery,Angularjs,Forms,这就是我的问题:我可以拥有这个对象数组: [{ "name": "Alex", "code": "05422180283", "pIva": "05422180283", "subCode": null }, { "name": "John", "code": null, "pIva": null, "subCode": "IT" }, { "name": "Billy", "code": null, "pI
[{
"name": "Alex",
"code": "05422180283",
"pIva": "05422180283",
"subCode": null
}, {
"name": "John",
"code": null,
"pIva": null,
"subCode": "IT"
}, {
"name": "Billy",
"code": null,
"pIva": null,
"subCode": "IT"
}, {
"name": "Tom",
"code": null,
"pIva": null,
"subCode": "IT"
}]
此json由ng repeat
在表单中使用,并且应填充空字段。当按下提交按钮时,系统应检查是否仍有空字段。所以现在的情况可能是这样的:
[{
"name": "Alex",
"code": "05422180283",
"pIva": "05422180283",
"subCode": null
}, {
"name": "John",
"code": "88985556",
"pIva": "1919ASVVV",
"subCode": "9991VVVV"
}, {
"name": "Billy",
"code": "89952366555",
"pIva": "BB588918989",
"subCode": "ASA234434"
}, {
"name": "Tom",
"code": null,
"pIva": "541198198",
"subCode": "ACEVV9999"
}]
如您所见,有两个空字段。在这种情况下,系统应通知用户有2个空字段。(发出警报或类似的声音)。否则,用户可以毫无问题地提交表单。这就是我到目前为止所做的:
angular.forEach($scope.myArray, function(items){
if(_.chain(items).find(_.isNull).isNull().value()) {
//console.log('Found one');
formHasEmptyFields = true;
} else {
//console.log('Did not find one');
formHasEmptyFields = false;
}
if(_(items).find(_.isNull) === null) {
//console.log('Found one');
formHasEmptyFields = true;
} else {
//console.log('Did not find one');
formHasEmptyFields = false;
}
});
if(formHasEmptyFields == true) {
alert('There are empty fields');
} else {
submitFunction($scope.myArray);
}
但它不起作用,因为它似乎只检查最后一个对象。事实上,如果我填写表单中的最后一个对象,它不会向我显示警报。有什么想法吗$scope.myArray
当然是我的对象数组请参见
const hasItemWhithFalsyCode = items.some(x => !x.code);
你可以做各种各样的事情,比如在没有代码的情况下过滤掉项目
const itemsWithTruthyCode = items.filter(x => x.code);
明确检查null
const hasItemWhithNullCode = items.some(x => x.code === null);
有关部分
const hasItemWhithFalsyCode = items.some(x => !x.code);
你可以做各种各样的事情,比如在没有代码的情况下过滤掉项目
const itemsWithTruthyCode = items.filter(x => x.code);
明确检查null
const hasItemWhithNullCode = items.some(x => x.code === null);
问题在于,尽管当存在
null
时,formHasEmptyFields
确实设置为true
,但在下一次迭代中,它会再次被false
覆盖
因此,要解决这个问题,只需设置formHasEmptyFields=false代码>一次,在循环之前和循环内部,只保留将其设置为true
的代码
话虽如此,一个some
或every
方法比一个forEach
循环更适用于这个场景。您可能想改用它。问题是,尽管formHasEmptyFields
在出现null
时设置为true
,但在下一次迭代中它会再次被false
覆盖
因此,要解决这个问题,只需设置formHasEmptyFields=false代码>一次,在循环之前和循环内部,只保留将其设置为true
的代码
话虽如此,一个some
或every
方法比一个forEach
循环更适用于这个场景。你可能想用它来代替。你能不能也附上你的html表格你能不能也附上你的html表格?那么,你主要的意思是删除else条件?确实,删除它们。那么,你主要的意思是删除else条件?确实,删除它们。确实,在这种情况下,使用some
比使用forEach
要好:一旦出现特定条件,它就会退出循环。如果您专门为他们的情况提供代码,这将对OP非常有用。事实上,在这种情况下,使用some
比使用forEach
要好:一旦出现特定条件,它就会退出循环。如果您专门为他们的案例提供代码,这将对OP非常有用。