Populating a multi-layered array using JSON data

My goal with this code is to populate a global array with JSON objects.

// declaring global arrays
var sectionL=[1,5,3,7,5,4,3,3,4,4,6,6,3,5,5,1];
var sectionsTitle=new Array(16);
var sectionsContent=new Array(16);
for(var i=0; i<sectionL.length;i++){
  sectionsTitle[i]=new Array(sectionL[i]);
  sectionsContent[i]=new Array(sectionL[i]);
}
var country = new Array(4);
 for(var i=0;i<5;i++){
 country[i]=new Array();  
 country[i][2]=sectionsTitle;// assigning as shown above 
 country[i][3]=sectionsContent;// assigning as shown above
//////////////////////////////////////

function getCountries(data){
 $.each(data['countries'], function (k,val){
 country[k][0]=val['title']; // storing the title
 country[k][1]=val['id']; // storing the id for JSON

  $.getJSON(baseURL+country[k][1]+'&callback=?',function(data ){
  console.log("k=>"+k+"  id=>"+country[k][1]); // checking if k is passed correctly
   for(var i=0;i<1;i++){
    index=i+1;
      for(var j=0;j<1;j++){
         country[k][2][i][j]=data['result']['sectionTitles']['section'+index+'.'+j+'.title']; // filling the array with content
      }
   }
 });
});



console.log(country); 

output:

[Array[4], Array[4], Array[4], Array[4], Array[4]]
k=>0  id=>9
k=>1  id=>29
k=>3  id=>31
k=>4  id=>12
k=>2  id=>7

Issue: The arrays are being overwritten, displaying only the last value. I suspect it's a closure problem, but I'm unsure how to proceed. Any suggestions would be helpful!

Answer №1

finally, it seems like the issue is

 country[i][2]=sectionsTitle;// assign as shown above 
 country[i][3]=sectionsContent;// assign as shown above

the problem arises because you are assigning the same objects to everything, causing them to reference the same object. One solution could be...

...

     country[i][2]=getSectionDetails(sectionL);// assign as shown above 
     country[i][3]=getSectionDetails(sectionL);// assign as shown above
...

function getSectionDetails(data){
    var details=[]
    data.forEach(function(v){ details.push([v]);});
    return details;
}

Previous:

I believe the issue lies in $.getJSON sharing the variable k with others. One possible solution would be...

function getCountries(data){
    var url;
     $.each(data['countries'], function (k,val){
         country[k][0]=val['title']; // store the title
         country[k][1]=val['id']; // store the id to send to the JSON
         url = baseURL+country[k][1]+'&callback=?';
         $.getJSON(url, onJSONData.bind({k:k, url: url}));  
    });
}


function onJSONData(data){
    var k = this.k;
    console.log("k=>",k,"  url=>",this.url, 'data =>', data); // just to check if k is passed
    country[k][2][0][0]=data.result.sectionTitles.section1[0].title; // fill the array with the content            
}

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 second JavaScript code consistently replaces the first code

I am implementing 2 different JavaScript references in my code, as shown below: <script src="../scripts/jsKeyboard.js" type="text/jscript"></script> <script src="../scripts/DOB_Validate.js" type="text/jscript"></script> To cal ...

problem encountered using arrays in C

int main() //custom task 10 { int numbers[10], index, counter = 0, minimumNum, maximumNum = 0, total = 0; for (index = 0; index < 10; ++index) { scanf("%d", &numbers[index]); if (numbers[index] > maximumNum) { ...

What could be causing the issue with ng-show in Angular?

When a user clicks on an icon, I want to display a drop-down menu. I attempted to use the ng-show directive for this purpose, but unfortunately, the drop-down menu is not appearing. I created an icon ..., and when clicked, I attempted to open the drop-do ...

"Enhance your web design workflow with Dreamweaver's ability to edit files

While coding in Dreamweaver CS5, I prefer using the code view exclusively. Recently, I came across the "dual screen" workspace feature which allowed me to eliminate distractions and focus solely on the main workspace with a secondary workspace in the corne ...

Issue with event binding on datepicker that is dynamically added is not functional

I have integrated the Kendo datepicker into my project, and I am facing an issue with duplicated div elements containing datepickers. The problem is that the datepicker events only fire once on the first duplicated div and then stop working altogether. I ...

Creating independent Javascript applications and HTML5 canvas games, optimized for V8 or tailored to the specific browser for optimal performance

Instead of solely targeting Chrome users due to browser performance issues, I am exploring alternative options to create an executable version of a canvas game. Is there a way to integrate v8 for non-Chrome users? Perhaps a web "wrapper" similar to Flash&a ...

Is it possible for me to choose to establish a new scope within a directive?

Encountered an issue while reusing a directive where some tags had a second directive with a new scope created using new or {}, while others did not have one. Attempting to create a new scope when one already existed resulted in an error being thrown by An ...

React problem with manipulating JSON arrays

In my React application, I am working with an array that looks like this: [ { year: 2014, field: "Coal", value: 100 }, { year: 2014, field: "power", value: 200 }, { year: 2014, field: "oil", value: 20 }, { ...

Mastering the art of jQuery UI development, similar to the techniques

I'm currently working on creating an abstraction layer for jQuery UI that enables the definition of Widgets as Objects, similar to ExtJS. Here's how it works: var mydialog = new $.ui.dialog({ modal:true, renderTo:'body', title:'T ...

Concealing Vimeo's controls and substituting them with a play/pause toggle button

I'm currently working on implementing the techniques demonstrated in this tutorial (), but unfortunately the code in the fiddle I put together doesn't appear to be functioning correctly. I'm at a loss as to what might be causing this issue. ...

Exploring the wonders of utilizing JSON with PHP

Struggling to find the right words as English is not my first language, but I'll try to keep it simple. I have a JSON page with data that I want to display on my website using a foreach loop. Here is a snippet of the JSON data: [{ "seller": "has ...

Creating a dynamic multidimensional array or object in AngularJS: tips and tricks

Below is the code snippet where I am attempting to dynamically construct an associative array in angularJs: $scope.details = {"profilesFound": [ "https: //twitter.com/alexandreagular", "https: //twitter.com/?profile_id=46130006", "https: //f ...

Creating a text design that spans two lines using Scalable Vector Graphics (SVG

I am working with an SVG that displays strings pulled from an Array... {"label":"Here is an example of the string...", "value":4}, The text above is shown in an SVG element as... <text>Here is an example of the string...<text> I would like ...

Why do some button clicks not trigger a page refresh in JavaScript?

Hey there, I have a situation where I have two buttons - one to add a dog to the dog list and another to clear the entire list. Both buttons are functioning properly, but I'm having an issue with only the OnSubmit button refreshing the page. The dog ...

Adding JavaScript files to a project in Ionic2 with Angular2 integration

I'm looking to incorporate jQuery into my Ionic2 app, which requires loading several JavaScript files: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <script type="text/j ...

Experiencing a version error in mongoDB when attempting to execute the save() function

I encountered a version error in MongoDB while using the save() method. After researching, I found out that the save method utilizes versioning. Trying to avoid this by using the update method led to another error stating "Performing an update on the path ...

Looking for a Discord Bot that can verify if a lengthy text block includes a keyword from a JSON file

I have developed a bot that is designed to check for messages containing a specific key with the value of "weak" and then send those keys back. However, I am encountering two issues with my code. When I input "!grading aban", the bot responds correctly. B ...

Why is the Google Maps API not displaying the map once the app is deployed on Heroku?

const express = require('express'); var app = express(); var bodyParser = require('body-parser'); var exphbs = require('express-handlebars'); var cors = require('cors'); //setting up the view engine app.engine(&apos ...

Angular displaying a slice of the data array

After following the example mentioned here, and successfully receiving API data, I am facing an issue where only one field from the data array is displayed in the TypeScript component's HTML element. Below is the content of todo.component.ts file im ...

What is the process of obtaining the ID and displaying the subsequent field based on that ID in Ruby on Rails?

I'm utilizing rails4 and I am looking for a more efficient way to display the sub-category list based on the category selected in a form. Currently, I have used JavaScript for this functionality but I believe there may be a better solution. Any sugges ...