-2

I have this array of object:

var arr = [
    { value : 'title', text : '' },
    { value : 'product', text : '' },
    { value : 'price', text : '' },
    { value : 'number', text : '' },
];

var error = false;

Now, I want to loop through this arr array of object and check if only one property (text) is NOT empty. If so then stop the loop and set the error variable to false otherwise true;

I am trying this code:

arr.every((item)=>{
    if (Object.values(item).includes(null)) {
        error = true;
    } else {
        error = false;
    }
}); 

but not working according to my expectation :(

Shibbir
  • 1,963
  • 2
  • 25
  • 48
  • 1
    `const err = arr.every(({ text }) => text != null && text !== "")` – Yousaf Jul 29 '22 at 06:25
  • @Yousaf will this code stop the loop when there is value on the text property and set the error as false? – Shibbir Jul 29 '22 at 06:27
  • Yes. See: [MDN - every()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every#description) – Yousaf Jul 29 '22 at 06:28
  • I don't understand why people put the negetive mark !! – Shibbir Jul 29 '22 at 07:58
  • As your question seems not to be answered yet i might have misunderstood your question and as such, my answer is not correct. So you want to break if ANY of the text values is empty or only if ALL are empty? – John_H_Smith Sep 02 '22 at 16:09

2 Answers2

0

You have to use try and catch.

Something like this :

var BreakException = {};

try {
  [1, 2, 3].forEach(function(el) {
    console.log(el);

    if (el === 2) throw BreakException;
  });

} catch (e) {
  if (e !== BreakException) throw e;
}

Reference

aLamp
  • 59
  • 1
  • 12
-3
arr.forEach((item)=>{
    if (!item.text) {
        error = true;
    } else {
        error = false;
    }
}); 

Maybe such? As you can directly use item as an object and reference with .text to its values.

John_H_Smith
  • 334
  • 2
  • 12