What is the syntax for implementing a nested for loop in JavaScript within this particular scenario?

var entries = [
    {
    "item": "something",
    "steps": [{
                "node": {"name": "test0"},
                "status": {"name": "test"},
                "time": {"name": "test"}
               },{
                "node": {"name": "test1"},
                "status": {"name": "test"},
                "time": {"name": "test"}
               }]
     }
];

customList = []

entries.forEach(data => {
    data.steps.forEach(step => {
        if (customList.indexOf(step.node.name) === -1) {
            customList.push(step.node.name)
        }
    });
});

I am attempting to append the name to a list only if it is not already present in the list. However, the code provided above seems to be malfunctioning.

Answer №1

When working with for...in loops in JavaScript, it's important to remember that they return strings, not objects. You have the option to treat the result as a string or parse it into an object before looping over it.

I noticed that you were redefining i, which would cause issues unless you create a different variable for your initial loop.

for (field in this.job[0].stages[i]) {
  console.log(field);
    for (node in this.job[0].stages[i][field]) {
      console.log(node);
      console.log(this.job[0].stages[i][field][node].name);
    }
}

EDIT:

Based on the information provided in the OP, I've corrected the syntax errors in your code snippet.

var data = [
  {
  "something": "something",
  "stages": [{
              "node": {"name": "test0"},
              "status": {"name": "test"},
              "time": {"name": "test"}
             },{
              "node": {"name": "test1"},
              "status": {"name": "test"},
              "time": {"name": "test"}
             }]
   }
];

nodeList = [];

data.forEach(obj =>
  obj.stages.forEach(stage => {
    if (nodeList.indexOf(stage.node.name) === -1) {
      return nodeList.push(stage.node.name)
    }
  })
);

Answer №2

Consider this:

function getNodeNames () {
  if (this.task[0].steps[0]) {
    for (let j = 0; j < this.task[0].steps.length; j++) {
      let nodeName = this.task[0].steps[j].node.name;
      if (nodeName) {
        console.log(nodeName); // "test"
      }
    }
  }
}

Answer №3

Like previously mentioned by others, the i is being used as a string here because it represents the name of a key in this scenario. To retrieve the value of i within your structure, you must reference the object using it once more:

getNodeName() {
  if (this.job[0].stages[0]) {
    for (index in this.job[0].stages[index]) {
      console.log(index);
      for (nodeIndex in this.job[0].stages[index].node) {
        console.log(node.name)
      }
    }
  }
}

Answer №4

After adding the object literal to the original post and correcting any syntax errors, it appears that the data object is an array of objects containing a property named stages.

Within each object in the stages array, there is another array of objects with a property called node, which in turn contains a property named name.

It's recommended not to use for..in loops for arrays due to unpredictable order. Instead, you can utilize forEach to achieve the desired results while keeping the code concise:

var data = [
    {
    "something": "something",
    "stages": [{
                "node": {"name": "test0"},
                "status": {"name": "test"},
                "time": {"name": "test"}
               },{
                "node": {"name": "test1"},
                "status": {"name": "test"},
                "time": {"name": "test"}
               }]
     }
];

data.forEach(obj =>
  obj.stages.forEach(stage => console.log(stage.node.name))
);

Answer №5

If you wish to display all the values of the name properties associated with each key such as node, status, and time, here's how you can achieve it:

var sampleJobs = [{
  "something": "something",
  "stages": [{
      "node": {
        "name": "node0-test"
      },
      "status": {
        "name": "status0-test"
      },
      "time": {
        "name": "time0-test"
      }
    },
    {
      "node": {
        "name": "node1-test"
      },
      "status": {
        "name": "status1-test"
      },
      "time": {
        "name": "time1-test"
      }
    }
  ]
}]

// The outer for loop iterates over the array containing job objects
for (i = 0; i < sampleJobs.length; i++) {
 
  // The inner for loop goes through the stages object within each job object
  for (j = 0; j < sampleJobs[i].stages.length; j++) {
    // This will print each object inside the stages array 
    // console.log(sampleJobs[i].stages[j]);

    // Assuming you want to display the value of the "name" property for each key, here is how to do it
    // This code snippet prints the name value for all keys present in the object
    
  Object.keys(sampleJobs[i].stages[j]).forEach(e => {
       console.log(sampleJobs[i].stages[j][e]["name"])
    })
 
  }

}

Note: Feel free to comment or uncomment the console statements included for understanding purposes.

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

After ReactDOM is used, the JavaScript code is no longer functioning properly

While working on my latest project, I utilized react.js and encountered an issue where javascript seemed to stop working when using ReactDOM to render a class extended from React.Component. I noticed that the alert() method would not work if it was placed ...

Issue with JavaScript ScrollTop

Simply put, I am trying to determine the total scroll size for a text area in a unit that scrollTop can align with. However, I am at a loss on how to do so. I've tried scrollHeight and various other methods without success. Any advice or suggestions ...

Tips for storing data from a table using a button

I have implemented a data table to display information from a database. I am looking for a way to save user information whenever they export data in Excel, CSV, or PDF format from the table. I have already created a function to handle saving user data, but ...

Trouble with Fetch in JS and PHP not sending parameters

Having trouble getting a PHP function to accept data from JavaScript, despite the PHP class working elsewhere in the application. The getTopFive() function works fine, but data insertion isn't happening as expected. Below is the code snippet along wit ...

Why is the defaultDate property not functioning properly in Material-UI's <DatePicker/> component with ReactJS?

I recently implemented the <DatePicker/> component from Material-UI ( http://www.material-ui.com/#/components/date-picker ) in my project. I encountered an issue while trying to set the defaultDate property to the current date on my computer, as it r ...

Exploring the differences between UTC and non-UTC date formats in Javascript

When working with JavaScript, I encountered a challenge in comparing two dates that are formatted differently. Specifically: 2015-09-30T00:00:00 and 9/30/2015 12:00:00 AM The former is in UTC format while the latter is not. Despite referring to the same ...

Utilizing Promises with Chained .then() Functions

I am struggling with simplifying the readability of my code. I have separated it into two main functions, but I am still dealing with nested .then() statements. I am looking for advice on how to structure these functions more effectively. It is important ...

NextJs Link component does not refresh scripts

While using the <Link> tag in NextJs for page navigation, I encountered an issue where my scripts do not rerun after switching pages. The scripts only run on the initial page load or when I manually reload the page. This behavior is different when us ...

When the AJAX function is called again, the previous loading process is interrupted, without the use of jQuery

I have created a function that loads a URL into an element, but it seems to be encountering issues when called repeatedly in a loop to load multiple elements. The current load operation stops prematurely: function loadDataFromURL(url, elementId) { var ...

Fetching data from a collection using Mongoose in Node JS

Currently working with MVC architecture. Seeking guidance on using the findOne({}) method in my loginController. I need to retrieve data from an existing collection, which already contains some information. My goal is simply to extract data from it. Apolo ...

Implementing a Timer on an HTML Page with JavaScript

I am looking to add a timer to my HTML page using JavaScript. The timer should get the selected date and time from an input field <input type="date" /> and control it. If the time difference between the current time and the selected time is less than ...

working with a list of Python objects in a JavaScript environment

Currently, I am building a web application using Flask and Python. In my Python code, I have a class that can be parsed as JSON. class uItem: itemCount = 0 def __init__(self, id, name): self.id = id self.name = name I am trying to acce ...

Utilizing Vue.js to showcase real-time data from a websocket in a table format and transmitting that data to a separate

Version: Using Vue CLI 2.6.x I'm currently facing two challenges: Challenge 1: Within my Vue application, I'm receiving continuous data updates through a websocket connection. Despite having content in the list (aqiDataList), the table does not ...

The fixed position setting does not anchor the elements to the bottom of a container

When applying the following styles: #fullpage-menu > .gradient { position: fixed; bottom: 0; left: 0; width: 100%; height: 0.3rem; } To the element with ID #fullpage-menu, which is styled as follows: #fullpage-menu { height: 100 ...

Using a function to identify and check dynamically added checkboxes

I am using a PHP page that loads a group of categories from another PHP script as checkboxes. Here is the format for the checkboxes: <input type='checkbox' class='cat-selector' id='Business' data-toggle='checkbox&apo ...

Programmatically simulate a text cursor activation as if the user has physically clicked on the input

I have been attempting to input a value into a text field using JavaScript, similar to the Gmail email input tag. However, I encountered an issue with some fancy animations that are tied to certain events which I am unsure how to trigger, illustrated in th ...

How can I increase the size of the nuka-carousel dots in React/Nextjs?

Looking for help on customizing the size of dots in my nuka-carousel. Unsure how to change their sizing and margin. ...

Undefined response received when parsing JSON data

Hey there, I'm currently working on an ajax request that submits a form and sends an email. If the email is successfully submitted, I encode a PHP array that has a structure like this: $success = array("state" => "Email Sent"); My issue arises wh ...

Is there a way for me to execute a function multiple times in a continuous manner?

I am attempting to create a blinking box by calling a function within itself. The function I have is as follows: $(document).ready(function(){ $("button").click(function(){ $("#div1").fadeToggle("slow"); }); }); <script src="https://a ...

How to identify the character encoding in a node.js request

Did you know that Facebook chat has a feature where it automatically detects and displays messages in a left-to-right format when typing in English, but switches to right-to-left style when adding right-to-left characters? I'm curious about how Faceb ...