Retrieve the JSON data by passing the variable name as a string

There are JSON files embedded in the page, like so:

<script type="text/javascript" language="javascript" src="json/divaniModerni.json"></script>
<script type="text/javascript" language="javascript" src="json/divaniClassici.json"></script>

All of them have the same structure with different elements:

var divaniModerni = {
"modelli": [
    {
        "nome": "California",
        "num": "5", 
    },
    {
        "nome": "Terra",
        "num": "6", 
    },
    {
        "nome": "Laura",
        "num": "7", 
    },
    {
        "nome": "Nonstop",
        "num": "11",    
    },
    {
        "nome": "Venere",
        "num": "8", 
    },
    {
        "nome": "Comfort",
        "num": "5", 
    },
    {
        "nome": "Infinity",
        "num": "8", 
    },
]

}

I can parse the file like this:

$(divaniModerni.modelli).each(function(index, element){ (...) }

Is it possible to dynamically change the file to parse by passing the name to a function like this?

function show(category)
{
    $(category.modelli).each(function(index, element){ (...) }
}

show(divaniModerni);

I tried using:

$(window[category].modelli).each(function(index, element){ (...) }

but it is not working...

EDIT:

Within the each loop, I am dynamically creating rows in a table based on the selected JSON elements:

$(divaniModerni.modelli).each(function(index, element){
            if (i == 1)
                row += "<tr>";
            row += "<td><figure><a class='thumbnails' rel='prettyPhoto[gallery" + i + "]' href='images/divani/" + element.nome + ".jpg'><img src='images/thumbnails/divani/" + element.nome + ".jpg' alt='" + element.nome + "'></a><div class='description'>" + element.nome;
            if (element.num > 0)
            {
                for (j = 2; j <= element.num; j++) 
                {
                    row += "<a style='display:none;' class='thumbnails' rel='prettyPhoto[gallery" + i + "]' href='images/divani/" + element.nome + j +  ".jpg'><img src='images/anteprima/divani/" + element.nome + j + ".jpg' alt='" + element.nome + "'></a>";
                }
            }
            row += "</div></figure></td>"; 
            if (i == category.modelli.length)
            {
                row += "</tr>";
                $('#show').append(row);
            }
            else if (i % 4 == 0)
            {
                row += "</tr>";
                $('#show').append(row);  
                row = "<tr>";  
            }   
            i++
        })

Answer №1

Directly pass the object reference into the each statement to iterate specifically on that object.

http://jsfiddle.net/b3zdahc0/

var divaniModerni = {
"modelli": [
    {
        "nome": "California",
        "num": "5", 
    },
    {
        "nome": "Terra",
        "num": "6", 
    },
    {
        "nome": "Laura",
        "num": "7", 
    },
    {
        "nome": "Nonstop",
        "num": "11",    
    },
    {
        "nome": "Venere",
        "num": "8", 
    },
    {
        "nome": "Comfort",
        "num": "5", 
    },
    {
        "nome": "Infinity",
        "num": "8", 
    }
    ]
};

function displayModels(category)
{
    $.each(category.modelli, function(index, element) {
               alert(index)
    });

}

$("button").on("click", function(e) { 
    displayModels(divaniModerni);
});

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

Emphasizing specific lines using an array

There is a block of text containing multiple lines, each wrapped within a span with an incremented value at the end (like line-1, line-2, line-3, and so on) to distinguish between them. <div id="textbody"> <span id="line-1">what is love< ...

Res.render() is failing to display content

I'm facing an issue with my express route where it's not rendering a jade template properly. If I provide the wrong jade template string, I get the usual error indicating that the file couldn't be found to render in the browser. However, wh ...

Ways to implement a percentage for scrollTop

I'm currently troubleshooting the code below. My goal is to understand why I'm unable to scroll the .post div with jQuery and input range properly using a percentage value like this: $("[type=range]").on('input',function(){ var v ...

borders in motion

I am currently working with this jQuery code. //this is the main javascript $(document).ready(function(){ $('nav.menu a').hover( function () { $('nav.menu').find(".current_item").removeClass("current_item"); ...

My onClick AngularJS function contains a for loop that is not functioning properly upon initial click

When I click on a student's name in my AngularJS app, the program is supposed to show the student's full name and list of tuitions. However, I am encountering an issue where the for loop does not work on the first click, but it works fine on the ...

Top method for achieving a smooth transition in a loading CSS3 animation

Having trouble implementing a fade in/fade out effect on a div with a CSS3 based login animation when a function is loaded. I have set up a jsfiddle but still can't get it to work. Any assistance would be greatly appreciated! http://jsfiddle.net/adam ...

The error "Facebook API offline conversion event parameter data must be in array format" has occurred

When attempting to upload events to Facebook's offline conversion dataset with custom fields, I encountered the following error: Status: 400 Response: { "error": { "message": "(#100) param data must be an ...

Exploring User Authentication and Permissions in React and Node.js?

Currently working on a new application that utilizes the complete MERN stack, and I find myself at a crossroads when it comes to implementing protected routes, user authentication, and assigning ACL user roles. In past projects using Node.js, I've re ...

Including 2D text onto a cube using elements from an array. Countless items

I have developed a script that generates approximately 10,000 boxes using the following code: var c=[]; c.push([13,0,3021,98,'01391A']); c.push([13,102,3021,98,'01391W']); c.push([13,204,3021,98,'01391Y']); c.push([13,306,302 ...

Creating a dynamic circle that expands in size based on the duration the user presses down (using Java Script)

I have a fun challenge for you! I want to create a growing circle on a canvas based on how long you hold your mouse button. Currently, I can draw a fixed width circle where my mouse was when I clicked, but I need it to dynamically change size as you hold t ...

My Action class is not being populated by the Struts2 JSON interceptor

Currently, I am working on developing a web application where the ExtJS JavaScript library is used to send requests with a JSON payload to my backend powered by Struts. Despite having confirmed that the correct method in my Action class is being called fro ...

Triggering a state in Reactjs from a different component: A step-by-step guide

Hey there, I could really use some assistance with this situation. Currently, I have a progress bar component and another component where I utilize the progress bar. Additionally, there is a third component that is meant to initiate the progress bar. Let ...

Optimal Approach: Utilizing Python3 to Parse Facebook JSON Data into MongoDB

I am currently exploring the most effective method to parse Facebook JSON responses into MongoDB. Sample FB Event JSON: { "description": "Event description", "name": "Event name", "place": { "name": "Place name", "location": { "city": ...

If the browser closes and there is no recipient to receive the data requested by my ajax, what ultimately becomes of that data?

On my website, utilizing vb.net / c# programming, there is javascript ajax code that retrieves data from the database and sends JSON back to the page. If, just before the ajax call is able to receive the JSON, the browser is closed or the page is redirect ...

Exploring the power of TypeScript within the useContext hook

I recently started following a React tutorial on YouTube and decided to convert the project from JavaScript to TypeScript. However, I am facing difficulties with implementing useContext in my code. Any help or guidance would be greatly appreciated. If yo ...

Creating a Social Media Platform with JavaScript, Bootstrap, JQuery, PHP, and Mysqil

I am currently in the process of developing a social networking platform that will have similar features as Instagram. Users will be able to log in, create posts, leave comments, like content, share posts, and send data to a server for storage or display p ...

How can we ensure that href/src values are "absolutized" when utilizing server rendering?

Imagine having an element with its href/src set as a root path like this: href="/abc/def". There is also a function written like this: function absolutizeHREF(href) { const URLBase = new URL(`http://${process.env.HOST}:${process.env.PORT}/`); ...

The icon in Material UI button is missing from the display

The button is functional, but the icon inside it isn't displaying correctly:https://i.sstatic.net/MXhIH.jpg Here is the code for the button: <Button color="secondary" aria-label="add an alarm"> <AlarmIcon></AlarmI ...

Unable to retrieve server data in Android listView

When working on JSON parsing in my TypeMenu Java file, I encountered an issue where the response from the server includes all items from the database instead of just the selected item. Ideally, when a user clicks on an item in the ListView, only that speci ...

Aligning a lowercase "i" element within a container

Is there a more effective way to center the "i" element within this div without using specific pixel margins that adjust based on hover? Below is my code snippet: HTML: <div class="nav-collapse"> <i class="fa fa-bars fa-2x" id="bars"></ ...