Working with JSON parsing in AngularJS without a specified element name

I am looking to extract data from a JSON response containing Country & State information. Here is the URL for the JSON data:

{
"China":  [
"Guangzhou",
"Fuzhou",
"Beijing",
"Baotou",
"Hohhot",
"Guiyang",
"Yinchuan",
"Nanjing",
"Changzhou",
"Chuzhou",
"Hefei",
"Jinan",
"Qingdao",
"Harbin",
"Zhaodong",
"Taiyuan",
"Xi'an",
.
.
.
 }
 ]

The desired output should look like this:

  • Guangzhou, China
  • Taiyuan, China

I am currently using AngularJS, and here is a snippet from my controllers.js file.

var
apiUrl = {
    countryStateList: 'https://gist.githubusercontent.com/mayurah/5f4a6b18b1aa8c26910f/raw/countriesToCities.json'
};

countryData.controller('countryDataCtrl', ['$scope', '$http', function($scope, $http) {
$http.get(apiUrl.countryStateList).success(function(data) {
    // console.log(data);
    $scope.countryStateList = data;
});
}]);

In my HTML file, the code looks similar to this:

<ul ng-repeat="country in countryStateList">
<li>{{ STATE_NAME, COUNTRY_NAME }}</li>
</ul>
  • STATE_NAME & COUNTRY_NAME are placeholders for display purposes. They should be replaced with Angular code.

The challenge lies in the fact that the JSON element names are the country names themselves. Any guidance on how to parse this data in AngularJS/Javascript would be greatly appreciated.

Answer №1

To begin, you can start by parsing the entire JSON data:

let jsonData = JSON.parse(RAW_JSON_STRING);
let modifiedData = [];

// Iterate through the JSON data
for (let key in jsonData)
{
    for (let index = 0; index < key.length; index++)
    {
        modifiedData.push(key[index] + ", " + key);
    }
}

There is no guarantee that the above code will function as expected.

Answer №2

In your scenario, utilizing ng-repeat may not yield the desired outcome. A custom directive would be more suitable for achieving the desired functionality.

<datalist id="stateCountry">
    <custom-datalist-option data-array="countryStateList"></custom-datalist-option>
</datalist>

Implement a directive function and generate an option utilizing it.

Feel free to check out the Updated Fiddle for reference.

I trust this information proves to be beneficial for your requirements.

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

Angular 2: Dynamically Adjusting View Components Based on URL Path

Apologies for the unconventional title. I struggled to come up with a better one. My goal is to develop an application with a simple 3-part structure (header / content / footer). The header should change based on the active route, where each header is a s ...

What is the process for modifying the popups associated with a polygon object?

As of now, every time I click on the map, a popup shows up with the name of the country based on a geoJSON file containing multi-polygon lnglat coordinates that outline the borders of each country. This method saves me from manually inputting each country& ...

Express.js - Monitoring for server closure

I have a Node.js application that utilizes Express. Within this application, there is a section of code structured as follows: const app = require('./app'); const port = process.env.PORT || 8080; const server = app.listen(port); server.on(&apos ...

Filtering JSON data using jQuery

Is there a way to narrow down a Google Spreadsheet JSON (like the one found here: ) so that I only receive the json-entry where the field contains "title":{"type":"text","$t":"test1"} or in other words, "where title = test1". All I am looking for from the ...

Issue in JavaScript on IE9: SCRIPT5022 error: DOM Exception - INVALID_CHARACTER_ERR (5)

I am encountering an error with the following line of code: var input2 = document.createElement('<input name=\'password\' type=\'password\' id=\'password\' onblur=\'checkCopy(th ...

simpleCart - Utilizing a modal window for easy input and sending the shopping cart data to PHP in a multidimensional array

Currently, I am working with the simpleCart JavaScript shopping cart, but I have encountered a minor issue. When a customer clicks "checkout," a modal pops up requiring them to enter their contact information. Upon submitting the form, an email is sent to ...

The callback function in JavaScript is not updating AngularJS unless it is written in shorthand form

Within an angular controller designed for user login functionality, the code snippets below are extracted from an angular-meteor tutorial: this.login = function() { Meteor.loginWithPassword(this.credentials.email, this.credentials.password, (e ...

Jackson is unable to deserialize a class with a single field, even though a Creator is

I am having trouble with a simple jUnit test that I have written: class MyTest { static class SingleField { int rank; SingleField(int rank) { this.rank = rank; } @Override public boolean equals(Obje ...

Is it possible to examine my API request URL from the API's perspective using a Linux Command Line Utility?

Curious to uncover the request URL I'm sending to a JSON API, as I suspect my URL parameters might be getting removed by a proxy server. How can I verify this information? Is there a method to view the request URI using tools like cURL, WGET, or any o ...

Reset the form upon submission in AngularJS

Hey, I'm looking to reset the form values after a successful submission. How can I achieve this? <div ng-controller="employeelistController as listControl"> <div class="container form-group" ng-controller="addEmployee as addemp"> ...

transform a nested JavaScript object into a one-dimensional array

There is a JavaScript object in the following format: { "draw": "", "columns": [ { "data": "userid", "name": "", "searchable": true, "search": { "value": "", "regex": false } } ] } I want to tra ...

The method continues to receive null values from Ajax despite successfully retrieving the data from Facebook

My current challenge involves creating a login using Facebook. The console indicates that the requested data (email, first_name, etc.) is being retrieved successfully, but for some reason, the AJAX request keeps sending null data to the PHP method. Below ...

Displaying a checklist that shows all items that have been selected, rather than only showing the first selected item

I'm facing an issue with my data table that has checkboxes corresponding to each row. My goal is to append the contents of the selected rows into a "Favorites List" when the checkbox is clicked. However, I am currently only able to display the content ...

Create a custom slider using jQuery that pulls in real-time data for a dynamic user

My goal is to implement a dynamic slider feature in my Django project by using jQuery and ajax. I have managed to create previous and next buttons for swiping through profiles with the help of others, but I am currently facing an issue with a NoReverseMatc ...

Volley network image viewer and HTTP request headers

When I receive a JSON response from the server, I need to populate a network image view in my Android app. The issue arises because the images are hosted on an IBM Domino server that requires user credentials. While using Volley for general requests, I ca ...

Creating a masterpiece on the final piece of paper

As someone who is new to programming with JavaScript and canvas, I have a function called drawLines(canvasIndex, startPosition) that is used to draw lines on a canvas. The function takes in two arguments: canvasIndex, which represents the canvas being draw ...

Prevent financial disagreement by utilizing jQuery carefully

While I'm sure this question has been asked in a similar form before, my searches for the $ sign did not return any results here. I have already built a large system and heavily utilized jQuery, using $ as a reference. Now, I don't want to rever ...

I need help on correctly retrieving the ng-model value in a controller when using it with the contenteditable directive

I've attempted using ng-change, ng-keypress, ng-keyup, and ng-keydown for this issue. Using ng-change, the ng-model value is being updated in the controller but not reflecting on the front end. However, with the other three methods, the value displa ...

Obtaining the date for the previous month using JavaScript or jQuery

I need to retrieve a specific date in JavaScript. My goal is to obtain the current date based on a variable named frequency, which can have values of Daily, Weekly, or Monthly. if(frequency=="daily") { date='current_date -2 days'; } e ...

Is there a way to automatically redirect a webpage based on the URL that is entered

Looking for a solution where a page checks a typed link upon loading, such as: www.test.com/myphp.php=10 If it detects a specific number, it should redirect to another link. For example: Upon finding www.test.com/myphp.php=10, it redirects to www. ...