What is the best method to loop through this object with JavaScript?

Suppose I have the following data:

let testData = {
  'numGroup1': [[(1, 2, 3, 4, 5), (5, 6, 7, 8, 9)]],
  'numGroup2': [[(10, 11, 12, 13, 14), (15, 16, 17, 18, 19)]]
};

What is the best approach to iterate through this data using JavaScript?

Answer №1

let sample_data = {
    'groupA': [[2, 4, 6, 8, 10], [12, 14, 16, 18, 20]],
    'groupB': [[22, 24, 26, 28, 30], [32, 34, 36, 38, 40]],
};

for(let key in sample_data){
    group = sample_data[key];
    for(let num in group){
        console.log(group[num]);
    }    
}

@Ian made a valid point... utilizing () will only return the last number of each group. It is advisable to use a multi-dimensional array instead.

        'groupA': [[2, 4, 6, 8, 10], [12, 14, 16, 18, 20]],
        'groupB': [[22, 24, 26, 28, 30], [32, 34, 36, 38, 40]],

Answer №2

Utilize the power of underscorejs for easy iteration

var example_data = {
    'groupA': [[1, 2, 3, 4, 5], [5, 6, 7, 8, 9]],
    'groupB': [[10, 11, 12, 13, 14], [15, 16, 17, 18, 19]],
};

_.chain(example_data).map(function(val, key) {
                   return val;
                }).flatten().each(alert);

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

Why isn't the page showing up on my nextjs site?

I've encountered an issue while developing a web app using nextjs. The sign_up component in the pages directory is not rendering and shows up as a blank page. After investigating with Chrome extension, I found this warning message: Unhandled Runtime ...

Ways to remove code from production during build process?

Is there a way to omit typescript code from getting bundled by webpack during build process? Let's say I have the following line of code in my app.ts file (a nodejs application): const thisShouldNotBeInProductionBundleJustInDevBundle = 'aaaaaaa ...

Access-Control-Allow-Origin does not permit the origin null

I've been searching for an answer to this question, but I haven't found a suitable one yet. let xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(){ if(xhr.readyState === 4 && xhr.status === 200){ let response = r ...

Swapping out one variable for another

After tweaking my code a bit, I'm still struggling to get it right. User input: !change Hi var A = "Hello" if (msg.content.includes ('!change')) { A = msg.content.replace('!change ', ''); } msg.send(A); //the change ...

Ways to separate a portion of the information from an AJAX Success response

I am currently working on a PHP code snippet that retrieves data from a database as follows: <?php include './database_connect.php'; $ppid=$_POST['selectPatientID']; $query="SELECT * FROM patient WHERE p_Id='$ppid'"; $r ...

Using the foreach Loop in Javascript and AngularJs

Having trouble with a foreach loop because you're not sure of the column name to access specific data? Here's a solution to display all columns along with their corresponding data: angular.forEach(data, function(value, key) { console.log( &a ...

Using HTML Select field to make ajax calls to web services

When working with modals that contain forms to create objects for database storage, there is a Select field included. This is the code snippet for the Select field: <div class="form-group" id=existingUser> <label>Username</label> < ...

Best Practices for Implementing JSON.stringify() with an AJAX Request

While I have a limited understanding of ajax and JSON, I am aware that using JSON.stringify in an ajax call can sometimes be beneficial. The ajax call below is functioning properly, whereas the one following it with the stringify method is not. I am unsure ...

React - utilize a variable as the value for an HTML element and update it whenever the variable undergoes a change

I'm on a mission to accomplish the following tasks: 1.) Initialize a variable called X with some text content. 2.) Render an HTML paragraph element that displays the text from variable X. 3.) Include an HTML Input field for users to modify the content ...

Stopping the page from refreshing on an ajax call in asp.net: a guide

Is there a way to prevent page refresh during an Ajax call? I have multiple views that open when a user clicks on a link button from a tree view. Currently, the views are refreshing the page with each button click. I would like to display a loading image ...

Tips for adding event listeners to dynamically-loaded content using AJAX

I need help with the following code snippet: $("#contantainer").load("some_page.txt"); Inside some_page.txt, I have the following content: <div class="nav"> <ul id="nav_ul"> <li><a class="nav_a" href="#home" id="home"> ...

Changing a button's value on click using PhoneGap

I've been working with phonegap and came across an issue with my buttons setup like this: <input id="my_button" type="button" onclick="my_function();"/> The goal is to capture the click event and change the button's value, my_function ( ...

Make sure a specific piece of code gets evaluated in a timely manner

To ensure the default timezone is set for all moment calls in the app's lifetime, I initially placed the setter in the entry point file. However, it turns out that this file is not the first to be evaluated. An issue arose with one of my reducers wher ...

How can I store an access token received from the backend (in JSON format) in local storage and use it to log in?

My goal is to create a login interface using Plain Javascript. I have obtained a Token from the backend and now need assistance in utilizing this Token for the login process and storing it in LocalStorage. Although I have successfully made the API call, I ...

Displaying a div in Vue.js when a button is clicked and an array is filled with

Hey there! I'm having an issue with displaying weather information for a specific location. I want to show the weather details in a div only when a button is clicked. Despite successfully fetching data from the API, I'm struggling to hide the wea ...

Attempting to transfer user information to MongoDB using AngularJS and Node.js

Greetings everyone! I am currently working on a template and trying to develop a backend for it, starting with the registration form. Despite having some kind of connection between my mongodb and my app, data is not being sent to the database. Here is the ...

Automatically selecting the map center while using the Drawing Manager feature for placing markers

My application utilizes the Google Drawing Library. When a user clicks on the Add New Marker Button, the Drawing Manager is activated allowing the user to generate a marker by clicking anywhere on the map. Subsequently, the following listener is executed: ...

What are some methods to boost productivity during web scraping?

Currently, I have a node script dedicated to scraping information from various websites. As I aim to optimize the efficiency of this script, I am faced with the challenge that Node.js operates on a single-threaded runtime by default. However, behind the sc ...

Tips for dynamically populating JSON data using a dropdown selection?

I am currently exploring HTML forms as a new web developer. I have been experimenting with displaying JSON data in a div based on a selection from a dropdown menu using jQuery in Chrome. However, my code does not seem to be functioning properly. Even tho ...

I'm looking for the best way to send POST data to an API with Meteor's HTTP package

Here's my current code snippet: HTTP.post("http://httpbin.org/post", {}, function(error, results) { if (results) { console.log(results); } else { console.log(error) } ...