Having trouble with looping through subarrays using Javascript and JSON

I am attempting to iterate through a JSON object using Javascript (jQuery). Within the main JSON object, each object in the array contains embedded arrays of tags.

My goal is to loop through all the files in the main object and simultaneously iterate through the tags, outputting them along with the files. The objects are first parsed before looping through them.

Here is the structure of the JSON object:

{
    "result": [
        {
            "id": "4f26f21f09ab66c103000sd00e",
            "file_url": "http://thefilesat.s3.amazonaws.com/81/0000/12.jpg",
            "tags": [
                "image",
                "elephants"
            ]
        },
        {
            "id": "4f2422c509ab668472000005",
            "file_url": "http://thefilesat.s3.amazonaws.com/9d/0000/7.jpg",
            "tags": [
                "image",
                "green",
                "tree"
            ]
        }
    ]
}

This code snippet below was my attempt, however it did not produce the desired result:

for (var i=0; i < parsed.result.length; i++) {

for (var j=0; j < parsed.result[i].tags.length; j++) {

    tags = '<div class="tag">' + parsed.result[j].tags[j] + '</div>';

};

html = '<div class="file""><img src="' + parsed.result[i].file_url + '" /><div class="tags">' + tags + '</div></div>';

$("#files").append(html);

};

Answer №1

The issue you're facing is that within the tags loop, you are utilizing the = operator, which ends up overwriting the variable you are assigning to in each iteration.

To resolve this problem, consider implementing something along these lines;

var html = '';

for (var i = 0; i < parsed.result.length; i++) {
    var tags = '';

    for (var j = 0; j < parsed.result[i].tags.length; j++) {
        tags += '<div class="tag">' + parsed.result[i].tags[j] + '</div>';
    };

    html += '<div class="file""><img src="' + parsed.result[i].file_url + '" /><div class="tags">' + tags + '</div></div>';
};

$("#files").append(html);

You also had used parsed.result[j].tags[j], when it should have been parsed.result[i].tags[j].

Furthermore, I've moved the appending to $('#files') outside of the loop so that it only executes once, reducing the number of DOM lookups and manipulations (which can be slow in relative terms).

Answer №2

Given the following:

parsed.result[j].tags[j]

I believe you intended to write:

parsed.result[i].tags[j]

Furthermore, make sure to use tags += instead of tags = to avoid overwriting the previous tag value.

Answer №3

We've identified a typo in the 3rd line that needs correcting:

tags = '<div class="tag">' + parsed.results[i].tags[j] + '</div>';

(it should be results[i] instead of j)

Answer №4

When working with objects and arrays, it is cost-effective to store an additional reference to the array:

var result = parsed.result; // new

for (var i=0; i < result.length; i++) {

    var tags = result[i].tags;  // new

    for (var j = 0; j < tags.length; j++) {
        tags += '<div class="tag">' + tags[j] + '</div>';
    }

    html = '<div class="file""><img src="' + result[i].file_url + '" /><div class="tags">' + tags + '</div></div>';
    $("#files").append(html);
};

At this point, repeating the index i in your innermost dereference becomes impossible.

This method also improves performance as the interpreter does not need to repeatedly dereference the entire chain of properties.

For what it's worth, a neater way to write this using jQuery without using the .html() method would be:

var result = parsed.result; // new
for (var i=0; i < result.length; i++) {

    var div = $('<div>', {'class': 'file'})
        .append('<img>', {src: result[i].file_url });

    var tags = result[i].tags;  // new
    for (var j = 0; j < tags.length; j++) {
       $('<div>', {'class': 'tag', text: tags[j]}).appendTo(div);
    }

    $("#files").append(div);
};

This approach eliminates string concatenation, quote mark escaping, and ensures correct escaping of any HTML special characters in your tags.

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

The active tab will dynamically update, however, clicking anywhere on the page will always bring you back to the first tab as

My view includes the following tabs: <div class="tabbable"> <ul class="nav nav-tabs padding-18"> <li class="active"> <a aria-expanded="false" data-toggle="tab" href="#Tab1"> <i class="green ac ...

React.js pagination - removing empty values from an array

I'm currently working on implementing pagination logic that automatically updates the page numbers when the last index is clicked. For example: 1 2 3 4 5 If a user clicks on the number 5, it should display: 2 3 4 5 6 and so forth... I have succe ...

Are there any methods to implement object-oriented programming in JavaScript?

The concept of prototype-based object-oriented programming in JavaScript is intriguing, but there are many scenarios where the need for class-based object creation arises. Consider a vector drawing application, where the workspace begins empty and you can ...

Optimizing the management of optional post fields in an Express.js application

When creating an endpoint with Express that includes both mandatory and non-mandatory fields in the post request, what is the optimal strategy for handling this? Would it be best to use something like if (field exists in req.body) { set variable } else { ...

Error 500 in WordPress Child Theme due to AJAX Internal Issue

I have encountered an issue with my Ajax code in the Js/Jq block (/buscador/menuLateral/menu-libros.php): $.ajax({ url: '<?= get_stylesheet_directory_uri(); ?>' + '/buscador/buscador-functions.php', type: 'POST' ...

Working with NodeJS: Utilizing object casting with default values and eliminating superfluous

In the backend code of a NodeJS application, there is an object defined as follows: { name : "foo" secret : "bar" } The objective is to return this object as JSON in response to an HTTP request without including the secret key. The desired return obj ...

Retrieving data from Firestore yields an empty result

Having trouble reading from Firestore within a function, even though writes are working fine. Despite following examples on the given link, the query below and its variations result in an empty promise: module.exports.customerByPhone = phone => { r ...

Creating a JSFiddle with sprites using source and image files from Github with THREE.JS - a step-by-step guide

Greetings! I am currently working on creating a JSFiddle based on the official THREE.js HUD Sprites example. However, I am facing an issue where the sprite images do not seem to load or apply using the URLs specified in the original file:- //... URL' ...

Utilizing JavaScript to assign object properties (column names) from an Array of Objects to a specific row and column header

I am currently in the process of implementing a mapping function to display data from an array of objects, initially stored in localStorage, into a table using Material-UI Table. The goal is to map all the specific column names into corresponding Table Ce ...

Selenium encountered an error when trying to execute the 'querySelector' function on the document. The selector provided, my_selector, is not recognized as a valid selector

Whenever I run this code: document.querySelector(my_selector) using selenium, an error is thrown: Failed to execute 'querySelector' on 'Document' my_selector is not a valid selector my_selector is definitely a valid selector that func ...

The map displayed on google.com appears different from the one featured on our website

The integration of the JS for the Google map on our website is working smoothly without any issues. However, when I zoom into our address on google.com/maps, our Hotel is listed as "Hotel". On the map displayed on our website, there are only a few entries ...

Trouble initiating Jquery on a dynamically generated table

I am currently working on a project in ASP.Net where I need to dynamically build an HTML Table. I have implemented the ability for users to resequence rows in the table, but I'm facing issues with the delegate events I've written. Sometimes they ...

The button's background color will vanish if you click anywhere outside the button or on the body of

Struggling with a tabpane created using HTML, CSS, and JavaScript. The problem arises when the background color of the active tab's button disappears upon clicking outside the button or on the body. While switching between tabs, I can change the color ...

Refreshing ng-model within a radio input

Currently, I am utilizing a jQuery library for radio/checkbox components. Although I am aware that combining jQuery with Angular is not ideal, the decision to use this particular library was out of my control and cannot be altered. One issue I have encount ...

Node.js is raising an error because it cannot locate the specified module, even though the path

Currently in the process of developing my own npm package, I decided to create a separate project for testing purposes. This package is being built in typescript and consists of a main file along with several additional module files. In the main file, I ha ...

Send the cookie with the JSON request

While logged into a secure website with a login, I came across some valuable data that is transmitted through the server in JSON format. By opening Chrome and inspecting the page using the "Network" tab, I discovered a URL utilizing XHR which contained the ...

Are there any modules in Angular 8 that are used across various projects?

I am facing a challenge with managing two projects that share the same core functionality. These projects have identical layouts and pages, but certain components and modules are specific to each project. Currently, I maintain two separate Angular projects ...

Converting JSON data into a format that can be easily displayed in a

There is this JSON file that my activity fetches and converts into a string: {"popular": {"authors_last_month": [ { "url":"http://activeden.net/user/OXYLUS", "item":"OXYLUS", "sales":"1148", ...

Iterating using a for loop within different functions

I am facing an issue with this project. I am planning to create a function that calculates from two different `for()` loops. The reason behind having 2 separate functions for calculation is because the data used in the calculations are fetched from differe ...

How can we know when a JavaScript ES6 arrow function comes to a close?

One thing I've been pondering is how an arrow function terminates when it lacks brackets. I encountered this issue when working with ReactJS, where I had a function followed by the start of a class declaration. Here's the snippet: const Search = ...