Storing JSON data in an array is a simple process that involves converting

Currently, I am working on implementing dependent dropdowns using JavaScript. The dropdowns include country, state, and city, with the data sourced from the JSON data provided below. My goal is to organize the data in such a way that countries are stored in a country array, states are stored in a state array based on the country selected, and cities are stored in a city array based on the state selected. While attempting this, I have made use of a for loop but unfortunately have only been able to access the innermost key value pair, which is the city field.

var country = {
        "Countries": [
            {
                "Country": "Country1",
                "states": [
                    {
                        "state": "state1",
                        "city": ["city1", "city2"]
                    },
                    {
                        "state": "state2",
                        "city": ["city1", "city2"]
                    }
                ]
            },
            {
                "Country": "Country2",
                "states": [
                    {
                        "state": "state3",
                        "city": ["city1", "city2"]
                    },
                    {
                        "state": "state4",
                        "city": ["city1", "city2"]
                    }
                ]
            }
        ]
}

Answer №1

Solution

My approach to solving the problem involved creating three separate arrays - one for countries, one for states, and one for cities. Each array contains relevant information along with references to other arrays for easy access:

Country Array

{
  country_id: index of country,
  country: name of country
}

State Array

{
  state_id: index of state,
  state: name of state,
  country_id: reference to country array
}

City Array

{
  city_id: index of city,
  city: name of city,
  state_id: reference to state array
}

By using the Array.prototype.filter function, I am able to retrieve states based on country ID and cities based on state ID.

Example Code

/**
 * Example
 * @type {Object}
 */
var country = {
    "Countries": [{
        "Country": "Country1",
        "states": [{
            "state": "state11",
            "city": ["city111", "city112"]
        }, {
            "state": "state12",
            "city": ["city121", "city122"]
        }]
    }, {
        "Country": "Country2",
        "states": [{
            "state": "state23",
            "city": ["city231", "city232"]
        }, {
            "state": "state24",
            "city": ["city241", "city242"]
        }]
    }]
};

/**
 * Default starting ID for state list
 * @type {Number}
 */
var state_id = 0;

/**
 * Default starting ID for city list
 * @type {Number}
 */
var city_id = 0;

/**
 * Array of country names
 * @type {Array}
 */
var country_array = [];

/**
 * Array of states (along with ID of country they belong to)
 * @type {Array}
 */
var state_array = [];

/**
 * Array of cities (along with ID of state they belong to)
 * @type {Array}
 */
var city_array = [];

/////////////////
// THE PROCESS //
/////////////////
country.Countries
    .forEach(function(each_country, country_index) {

        country_array
            .push({
                country_id: country_index,
                country: each_country.Country
            });

        each_country.states
            .forEach(function(each_state) {

                state_array
                    .push({
                        state_id: state_id,
                        state: each_state.state,
                        country_id: country_index
                    });

                each_state.city
                    .forEach(function(each_city) {

                        city_array
                            .push({
                                city_id: city_id,
                                city: each_city,
                                state_id: state_id
                            });

                        city_id = city_array.length; // Calculating the next city_id
                    });

                state_id = state_array.length; // Calculating the next state_id
            });
    });

/**
 * Returns array of countries
 * @return {[Object]} Array of countries
 */
var getCountryList = function() {
    return country_array;
};

/**
 * Returns array of states belonging to a country
 * @param  {Number}   country_id The index of the country in the country array
 * @return {[Object]}            Array of states
 */
var getStateList = function(country_id) {
    return state_array
        .filter(function(each) {
            return each.country_id === country_id;
        });
};

/**
 * Returns array of cities belonging to a state
 * @param  {Number}   state_id The index of the state in the state array
 * @return {[Object]}          Array of cities
 */
var getCityList = function(state_id) {
    return city_array
        .filter(function(each) {
            return each.state_id === state_id;
        });
};

// Retrieve the country list
getCountryList();

// Retrieve the state list of country with ID 0
getStateList(0);

// Retrieve the state list of country with ID 1
getStateList(1);

// Retrieve the city list of state with ID 0
getCityList(0);

// Retrieve the city list of state with ID 1
getCityList(1);

Answer №2

You have the ability to utilize the reduce() method in order to consolidate all city or state key/value pairs into one object.

var country = {
  "Countries": [{
    "Country": "Country1",
    "states": [{
      "state": "state1",
      "city": ["city1", "city2"]
    }, {
      "state": "state2",
      "city": ["city1", "city2"]
    }]
  }, {
    "Country": "Country2",
    "states": [{
      "state": "state3",
      "city": ["city1", "city2"]
    }, {
      "state": "state4",
      "city": ["city1", "city2"]
    }]
  }]
}

var result = country.Countries.reduce(function(r, e) {
  r.country = (r.country || []).concat(e.Country);
  e.states.forEach(function(a) {
    r.state = (r.state || []).concat(a.state);
    r.city = (r.city || []).concat(a.city);
  })
  return r;
}, {})


console.log(result)

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

Creating a 2D Image Display in three.js

I'm facing a challenge with my threejs project. My goal is to have a 2D image appear on the screen when I press a key. I've done some research but haven't been able to find a solution that works for me. The methods I've tried either don ...

My strategies for addressing caching problems in my ReactJS site

Currently tackling ReactJS projects on a website with the URL . Things seem to be running smoothly, until my SEO-savvy friend pointed out an issue with caches. He advised me to visit this cache URL: , where Google should display the main page but instead s ...

Unable to update content within the `style` attribute when the HTML is stored in a variable

I am attempting to make changes to the style html - specifically by replacing a string, but unfortunately it is not functioning as expected. I am struggling to obtain the final updated html. Below is my attempt: var html = "<style>043BF83A8FB24A418 ...

Exploring the world of jQuery animation and background colors with Animate()

I'm currently attempting to implement a basic pulse effect by utilizing JQuery to modify the background color. However, I am facing issues with animating the backgroundColor property. function show_user(dnid) { /* dnid represents the HTML ID of a ...

Combining ReactJS event handling for onClick and onKeyDown into a single handler for TypeScript

To ensure accessibility compliance, I am incorporating onKeyPress handlers into my application. However, I am facing a challenge with interactive <div /> elements. Here are the event handlers I want to trigger on click: const handleViewInfoClick = ( ...

Executing a function defined in a .ts file within HTML through a <script> tag

I am attempting to invoke a doThis() function from my HTML after it has been dynamically generated using a <script>. Since the script is loaded from an external URL, I need to include it using a variable in my .ts file. The script executes successfu ...

Parsing JSON data with dynamic nested property names

Looking for advice on deserializing a complex JSON response from an external REST API using System.Text.Json in .NET 6. Here's the situation: I have a model defined for the data: class DeviceData{ //lots of properties } When querying for a singl ...

Issue encountered while attempting to attach an event listener to an element within a class

Upon running the code, I encountered an error message that reads: Uncaught TypeError: this.startButton.addEventListener is not a function and I'm unsure of how to resolve it. Although I can successfully console.log the button inside the class, adding ...

Is there a way to attach an event for multiple arithmetic operations to a checkbox?

My form includes 4 checkboxes for different mathematical operations. <form action="" method="POST"> Select number of questions: <input type="number" name="que" value="que"> <br> <br> Select number of series: <select name="sel ...

I keep encountering an Uncaught TypeError when trying to read the property 'options' of null, despite having the element ID properly defined

I am a newcomer to the world of Javascript and HTML. Despite having the element defined in HTML, I am encountering an exception. Could someone please offer assistance? My goal is to create a shape (initially a circle) based on user input such as shape type ...

Transforming text input into an array of text in PostgreSQL

I have a table named t1 id | names ----|------------------------- 1 | {jully , alex , sarah} 2 | {bety , cate , jenifer} 3 | {adam , pit , joee} 4 | {piter , mat , andy} My goal is to retrieve rows that contain at least one name starting wi ...

Embracing either dark or light mode

Can anyone give advice on how to integrate a feature like this onto my website? I've attempted to use plugins with no success. It doesn't need to be too complex. Does anyone have experience with this or know of a solution they could suggest? Alt ...

Integrate the BloomEffect from Post processing in Three.js

I encountered an issue while trying to implement post-processing effects. const renderer = new THREE.WebGLRenderer() renderer.setSize(sizes.width, sizes.height) document.body.appendChild(renderer.domElement) const composer = new EffectComposer(renderer) ...

Guide on converting JSON array values into CSV format with JQ

I have a JSON file that stores information about different application clients along with their respective features: { "client-A": [ "feature-x" ], "client-B": [ "feature-x", "feature-y" ], "client-C": [ ...

What is the best way to change a date-containing string into a Json object?

I need to convert a string into a JSON Object using JavaScript. However, when I do so, the date in the original string gets completely changed. Here is the string I am working with: var JsonData=[[2013-02-27,787],[2013-02-26,131],[2013-02-02,0],[2013-01- ...

JavaScript, keep it easy: globalize

Looking for help with a simple regex expression... document.getElementById('testing').value=f2.innerHTML.replace(">",">\n"); I'm having an issue where it only stops after the first line break. How can I make it work for the enti ...

Altering the context of 'this' with the bind method in JavaScript

When using bind to change the scope of 'this', it allows me to reference my generateContent function using 'this' within the click function. However, this adjustment causes the this.id to no longer work due to the changed scope. Is the ...

Retrieve the key and corresponding value from the columns field within a Postgresql table

id | columns | timestamp | query_id | task_id -------+----------------------------------------------+----------------------------+----------------------+--------------------- ...

Retrieve a JSON reply for Android devices

Looking to create a straightforward Celsius to Fahrenheit converter in a Django server. The Django Backend is functioning correctly, but I just need a simple method to retrieve and display that information in an Android app: URL: 192.168.1.212:8000/c_f/ ...

AddDeviceModalCtrl is not defined as a function, it is showing as undefined

I am encountering the error mentioned above, I suspect that it is due to the controller not being properly attached to the module. However, I could be mistaken. Below is the definition of the controller. (function () { 'use strict'; angular . ...