-2

const arr = [{id: 1, name: '123', price: 11, discount: 0, quantity: 1, total: 1}, {id: 2, name: '123', price: 11, discount: 0, quantity: 1, total: 1}];
const productsValidation = (data) => data.every(
    ({ id, name, price, discount, quantity, total }) =>
      id && name && price && discount && quantity && total
  );

console.log(productsValidation(arr));

I want to check if the objects in the array contain the values ​​I expect, but for some reason every returns false. Why?

Лукас
  • 213
  • 1
  • 4
  • 12
  • 3
    Because `discount` has a value of `0` which is falsy. If you simply want to check if one or more key(s) exists, then use `Object.keys` to get all the keys and intersect it with an array of keys you expect the object to have, or use ` in `. It’s not clear what you’re trying to check for in your code tho. – Terry Jun 10 '21 at 21:36
  • @Terry Oh really, thanks for the hint – Лукас Jun 10 '21 at 21:36

1 Answers1

1

Because discount: 0 is boolean false.

Explanation:

id && name && price && discount && quantity && total

will be true if and only if EVERY item is truey. 0 is not truey in Javascript, so the logical expression will evaluate to false, because 0 is the value of discount

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
  • This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/low-quality-posts/30206736) – Stefano Amorelli Oct 29 '21 at 08:55
  • 1
    @StefanoAmorelli This is the actual answer. I have edited it to elaborate what the answerer was meaning, but even in its original form it provides a concise answer. A short answer is still an answer. – Lajos Arpad Oct 29 '21 at 11:15