skip to Main Content

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

2

Answers


  1. You can use a different method loop, as the object form is relatively simple and there are many ways to view properties.

    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 passedValue = null;
    for(let i=0;i<jobs.length;i++){
        if(jobs[i].hasOwnProperty('Invoice Net')){
        //if(jobs[i]['Invoice Net']){
            passedValue = jobs[i]['Invoice Net'];
            break;
        }
    }
    console.log(passedValue); // €120.00
    
    Login or Signup to reply.
  2. 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"
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search