Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to find property in array of object and stop looping

I have an array of objects

const jobs = [
{   "id": 1,
    "title": "Item 1",
    "Invoice Net": "€120.00",
    "Invoice VAT": "€0.00",
    "Invoice Total": "€120.00"
},
{   "id": 2,
    "title": "Item 2",
},
{   "id": 3,
    "title": "Item 1",
    "Invoice Net": "€200.00",
    "Invoice VAT": "€20.00",
    "Invoice Total": "€240.00"
},

];

I want to loop through the array and then through its objects to find the first existing "Invoice Net" key. When the key is found I want to pass its value to the variable and stop looping.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My solution so far is

let passedValue = null;

jobs.forEach((job) => {
  if('Invoice Net' in job){
    passedValue = job['Invoice Net'];
    
}
 break;
})

It’s obviously not working as the break statement is not allowed in forEach loop

>Solution :

const jobs = [
    { "id": 1, "title": "Item 1", "Invoice Net": "€120.00", "Invoice VAT": "€0.00", "Invoice Total": "€120.00" },
    { "id": 2, "title": "Item 2" },
    { "id": 3, "title": "Item 1", "Invoice Net": "€200.00", "Invoice VAT": "€20.00", "Invoice Total": "€240.00" }
];

let invoiceNetValue;

for (const job of jobs) {
    if (job["Invoice Net"] !== undefined) {
        invoiceNetValue = job["Invoice Net"];
        break;  // Exit the loop once the first "Invoice Net" is found
    }
}

console.log(invoiceNetValue);  // Output: "€120.00"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading