5

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

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

Thanks

2
  • 2
    If you want to verify all entries without hardcoding property names then: const validation = items.every(i => Object.values(i).every(v => v)); Commented Apr 24, 2020 at 18:53
  • 1
    @AmirPopovich that works thanks man Commented Apr 24, 2020 at 19:38

2 Answers 2

10

You could take Array#every

The every() method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.

and get true if all values are not falsy.

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);

Sign up to request clarification or add additional context in comments.

Comments

1

Refer below code validation will give true if array doesn't contain empty object else it will give false.

you shouldn't compare each property of object , instead compare object length each time

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.