[英]How to check if array of object's properties are empty in javascript
I'm trying to make a validation in js to check if array of objects' properties are empty strings or not, to clarify more, i have an array that has objects inside, and i want to check for each object if it has an empty property (""), here is the code i've written but i'm not sure this is the correct way我正在尝试在 js 中进行验证以检查对象的属性数组是否为空字符串,为了进一步澄清,我有一个内部包含对象的数组,我想检查每个 object 是否为空属性(“”),这是我写的代码,但我不确定这是正确的方法
const items = [
{ name: "something", quantity: "25", unit: "d" },
{ name: "something", quantity: "25", unit: "d" },
{ name: "something", quantity: "25", unit: "d" },
];
const validation = items.map((item) => {
return Boolean(item.name && item.quantity && item.unit);
});
But it is just giving me an array like this:但它只是给了我一个这样的数组:
[true, true, true]
It is like i want it to only give me the value true if all of the properties are not empty如果所有属性都不为空,就像我希望它只给我值 true
Thanks谢谢
You could take Array#every
你可以拿Array#every
The
every()
method tests whether all elements in the array pass the test implemented by the provided function.every()
方法测试数组中的所有元素是否通过提供的 function 实现的测试。 It returns a Boolean value.它返回一个 Boolean 值。
and get true
if all values are not falsy.如果所有值都不是假的,则为true
。
const items = [ { name: "something", quantity: "25", unit: "d" }, { name: "something", quantity: "25", unit: "d" }, { name: "something", quantity: "25", unit: "d" }, ]; const validation = items.every(item => item.name && item.quantity && item.unit); console.log(validation);
Refer below code validation will give true if array doesn't contain empty object else it will give false .如果数组不包含空 object ,请参阅下面的代码验证将给出true ,否则它将给出false 。
you shouldn't compare each property of object, instead compare object length each time您不应该比较 object 的每个属性,而是每次比较 object 长度
const items = [ { name: "something", quantity: "25", unit: "d" }, { name: "something", quantity: "25", unit: "d" }, { name: "something", quantity: "25", unit: "d" }, ]; let validation=true; for(let i=0;i<items.lenght;++i){ if(Object.keys(items[i]).length===0) { validation =false; break; } } console.log(validation);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.