Search code examples
javascriptecmascript-5

javascript how to loop and get the first satisfied condition object with the respective index and parent index


Here is my data set object set, i want to iterate and need the result of below noted item:

var data = [
    { 
        name: 'sam', 
        id: 12235,
        qccheck: { hit: false},
        company: [
                   {
                      name: 'comp1' , 
                      Id: 5356,
                      qccheck: { hit: false},
                   },
                   {
                      name: 'comp2' , 
                      Id: 7645,
                      qccheck: { hit: true},
                   }
                ]
   },
   { 
        name: 'mark', 
        id: 8877,
        qccheck: { hit: true},
        company: [
                   {
                      name: 'comp3', 
                      Id: 3865,
                      qccheck: { hit: true},
                   },
                   {
                      name: 'comp4', 
                      Id: 87546,
                      qccheck: { hit: false},
                   }
                ]
   }
]

i) first condition ('qccheck: { hit: true}') satisfied object item. i.e: the result should be

  {
      name: 'comp2' , 
      Id: 7645,
      qccheck: { hit: true},
   }

ii) and the index of both condition satisfied object and the parent object i.e: the result should be 'data index = 0' and child `'company index=1'

so basically after iteration of the loop i want to know the first condition satisfied object and the index of that object as well as the parent object index

can anyone suggest the best way to achieve that?


Solution

  • A simple double for loop should do the trick

    var obj = null;
    var data_index = -1;
    var company_index = -1;
    
    for (var i = 0; i < data.length; ++i)
    {
      if (data[i].qccheck.hit)
      {
        obj = data[i];
        data_index = i;
        break;
      }
    
      if (!data[i].company) continue;
      for (var j = 0; j < data[i].company.length; ++j)
      {
        if (data[i].company[j].qccheck.hit)
        {
          obj = data[i].company[j];
          data_index = i;
          company_index = j;
          break;
        }
      }
    
      if (obj) break;
    }