Nested for loop in JavaScript causing the display of only the final value of the iterating object

When constructing a JSON array object using two different arrays, I noticed that the value of the last iterated value is being assigned to every element in the array. Specifically, for the serial number element, only the last iterated value is being displayed. Is there something crucial that I might be overlooking?

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);
    }
  }
}

Answer №1

This code snippet simplifies the debugging process

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
          });
        }
      }
    }
  }
}

Alternatively

const meter = postAdvancedAddressCheckRequest.addressCheck.energyQuoteAddress.electricityMeter,
  matches = ecoesGetTechnicalDetailsByMpanResponse.Results[0].UtilityMatches;
meters.forEach(meter => {
  matches.forEach(match => {
    match.Meters.forEach(meter => {
      meter.MeterDetails.forEach(detail => {
        if(detail.Key === "meter_serial_number") {
          electricityArray.push({
            "Check": true,
            "serialNumber": matches[i].Meters[j].MeterDetails[k].Value
        });
      })
    })
  })
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error: The term 'RequestCompleted' is not recognized by Microsoft JScript

Does anyone have any suggestions? The error above occurs when this code is executed: Sys.WebForms.PageRequestManager.getInstance().add_endRequest(RequestCompleted); Specifically within this section: <script language="javascript" type="text/javas ...

I'm having trouble executing the JavaScript function

function contentChange(){ var paragraphs = document.getElementsByTagName("p"); for(var i = 0 ; i < paragraphs.length ; i++){ paragraphs[i].innerHTML = "hello" ;}} contentChange(); I'm struggling to change the content of all ...

transforming an array-containing string into a JSON format object

When making SOAPUI requests, the responses are in string format, regardless of their content. At time t, a request returns the following string: {satisfied=true, dynamic_href/properties/triggers, name=triggers, value={satisfied=true, dynamic_href/properti ...

Understanding how to extract a specific value key from a JSON object in Typescript while utilizing Angular can greatly

I'm currently facing a challenge in Typescript with Angular where I need to retrieve a specific value from a JSON constant. While I am aware of the performance implications, I am wondering if there is a more efficient way to access this value within t ...

What is the reason for the excessive width of the final column in this table?

I am currently working with a dataset that I am displaying using the handsontable library in the form of a table. One issue I am facing is that the last column of my table appears too wide even though I did not specify any width for it. Below you can see t ...

Passing arrow functions for input validation rules to the Stancil component in Vue

I am attempting to implement an arrow function as input rules, similar to the setup in Vuetify at https://vuetifyjs.com/en/api/v-input/#rules. My approach involves passing rules within an array using the following code: <body> <div id="ap ...

Detection of collisions using bounding sphere method

In Three.js, each mesh (THREE.Object3D) comes with useful properties like boundingSphere and boundingBox, along with methods such as intersectsSphere and isIntersectionBox. I initially thought I could use these for simple collision detection. However, I n ...

Implementing a document update event using jQuery

On my WordPress site, I am using a responsive lightbox plugin. When an image is clicked, it opens a popup box with the ID fullResImage. Now, I would like to incorporate the Pinch Zoomer function to it. Do I need to bind a function for this, or is there a s ...

Error: The XML parsing in ASP failed to find a root element at the specified location

When clicking the button, I have jQuery/Ajax code that is supposed to pass the value of a selected radio button to a controller action and open a detail page. However, I am encountering an error. When using Mozilla Firefox, the console displays: XML Par ...

I am wondering why the JSON data retrieved through $http.get and stored in the $scope object is not displaying in the binding expression

After retrieving JSON data from a JSP file in AngularJS, I stored it inside a $scope object. However, the data was not displaying when I tried to print it within the binding expression. Strangely, the data was visible in the console log when using console. ...

Switching Next.js JavaScript code to Typescript

I am currently in the process of transforming my existing JavaScript code to TypeScript for a web application that I'm developing using Next.Js Here is the converted code: 'use client' import React, { useState, ChangeEvent, FormEvent } fro ...

Is it possible to run my JavaScript script immediately following the execution of npm run build?

Hey everyone! I am trying to run my JavaScript file right after receiving the successful message from npm run build. Currently, I am working on a Vue.js codebase. Is there a way for me to log and create a file in my code repository containing the 'run ...

Do you think my plan to develop an HTML parser from the ground up will be successful?

My goal is to enhance my skills by building an HTML parser. The basic idea I have in mind includes: Defining the tokenization using regex. Taking a string of HTML as input. Iterating through the HTML string. Storing details about each token, such as cont ...

Tips for centering a div horizontally when it exceeds the width of a mobile screen

My challenge is to create a circular div element that is wider than the mobile screen and perfectly centered. This circular div needs to be an exact circle, specifically targeted for mobile screens. I've attempted to achieve this using the code in th ...

What could be causing my for loop to unexpectedly terminate early?

I'm currently tackling a challenge on CodeChefs: My task is to find the smallest missing positive integer in an unsorted list of numbers. Here's the code snippet I've implemented: var firstMissingPositive = function(nums) { nums.sort(); ...

Navigating the storing and organizing of user data through Firebase's simplistic login feature for Facebook

As I work on my AngularJS and Firebase-powered website project, I aim to leverage Facebook login for seamless user connectivity. While Firebase's simple login feature promises an easier authentication process, I face the challenge of effectively acces ...

Vue - the <script setup> element is unable to execute scripts

I have a functional widget from Atlassian that works as expected when used in an HTML file: <html lang="en"> <head> <script data-jsd-embedded data-key=<key> data-base-url=https://jsd-widget.atlassian.com src=https://jsd-w ...

Tips to prevent encountering the "The response was not received before the message port closed" error while utilizing the await function in the listener

I'm currently in the process of developing a chrome extension using the node module "chrome-extension-async" and have encountered an issue with utilizing await within the background listener. In my setup, the content.js file sends a message to the ba ...

Using v-model in Vue with jQuery integration

I wrote a jQuery code that is executed when the mounted hook runs mounted() { this.$progress.finish(); var geocoder = new google.maps.Geocoder(); var marker = null; var map = null; function initialize() { var $latitude = document.getEl ...

Maintain scrolling at the bottom with React.js

Is there a way to make a div element increase in height through an animation without extending beyond the viewable area, causing the window to automatically scroll down as the div expands? I am looking for a solution that will keep the scroll position lock ...