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.
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
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"