Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
179 views
in Technique[技术] by (71.8m points)

json - JavaScript nested for loop resulting in displaying only last iterating object value

I have a json array object which is getting constructed using two different array objects. But after looping I'm getting the value of the last looped value for every array.

But for the serial number element I'm getting the value of the last iterated value. Am I missing something?

for (z = 0; z < postAdvancedAddressCheckRequest.addressCheck.energyQuoteAddress.electricityMeter.length; z++) {
  for (i = 0; i < ecoesGetTechnicalDetailsByMpanResponse.Results[0].UtilityMatches.length; i++) {
    for (j = 0; j < ecoesGetTechnicalDetailsByMpanResponse.Results[0].UtilityMatches[i].Meters.length; j++) {
      for (k = 0; k < ecoesGetTechnicalDetailsByMpanResponse.Results[0].UtilityMatches[i].Meters[j].MeterDetails.length; k++) {
        if (ecoesGetTechnicalDetailsByMpanResponse.Results[0].UtilityMatches[i].Meters[j].MeterDetails[k].Key === "meter_serial_number") {
          var serialNumber1 = ecoesGetTechnicalDetailsByMpanResponse.Results[0].UtilityMatches[i].Meters[j].MeterDetails[k].Value;
        }
      }
      electricityMeterObject = {
        "Check": true,
        "serialNumber": serialNumber1
      }
      electricityArray.push(electricityMeterObject);
    }
  }
}
question from:https://stackoverflow.com/questions/65870497/javascript-nested-for-loop-resulting-in-displaying-only-last-iterating-object-va

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is easier to debug

const meter = postAdvancedAddressCheckRequest.addressCheck.energyQuoteAddress.electricityMeter,
  matches = ecoesGetTechnicalDetailsByMpanResponse.Results[0].UtilityMatches;
for (let z = 0; z < meter.length; z++) {
  for (let i = 0; i < matches.length; i++) {
    for (let j = 0; j < matches.Meters.length; j++) {
      for (let k = 0; k < matches[i].Meters[j].MeterDetails.length; k++) {
        if (matches[i].Meters[j].MeterDetails[k].Key === "meter_serial_number") {
          electricityArray.push({
            "Check": true,
            "serialNumber": matches[i].Meters[j].MeterDetails[k].Value
          });
        }
      }
    }
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...