Generate an array by combining data from various JSON files

Greetings, I have an array containing various cities:

var cityArr = ["London", "Beijing", "Paris", "New York", "Seoul", "HongKong"];

My goal is to iterate through each city and retrieve JSON data using AngularJS and JavaScript. Here's the code snippet:

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

    $scope.$watch('fondCity', function () {
        cityService.city = $scope.foundCity;
    });
    var newUrl = "http://api.waqi.info/feed/" + cityArr[i] + "/?token=5336bd836b9ec064f6c6fe0bf7e2781838c15c87";
        $http({
            method: "GET",
            url: newUrl
        }).then(function mySucces(response) {
            $scope.newData = response.data;

        }, function myError(response) {
            $scope.newData = response.statusText;
        });
    }

Now, the question arises: How can I merge all these JSON files into a single array?

Here's an example of a single JSON file:

{
  "status": "ok",
  "data": {
    "aqi": 49,
    "idx": 5724,
    "attributions": [
      {
        "url": "http://uk-air.defra.gov.uk/",
        "name": "UK-AIR, air quality information resource - Defra, UK"
      },
      {
        "url": "http://londonair.org.uk/",
        "name": "London Air Quality Network - Environmental Research Group, King's College London"
      }
    ],
    "city": {
      "geo": [
        51.5073509,
        -0.1277583
      ],
      "name": "London",
      "url": "http://aqicn.org/city/london/"
    }
}  

I envision the final merged array looking something like this:

{
  "status": "ok",
  "data": {
    "aqi": 49,
    "idx": 5724,
    "attributions": [
      {
        "url": "http://uk-air.defra.gov.uk/",
        "name": "UK-AIR, air quality information resource - Defra, UK"
      },
      {
        "url": "http://londonair.org.uk/",
        "name": "London Air Quality Network - Environmental Research Group, King's College London"
      }
  "status": "ok",
  "data": {
    "aqi": 155,
    "idx": 1451,
    "attributions": [
      {
        "url": "http://www.bjmemc.com.cn/",
        "name": "Beijing Environmental Protection Monitoring Center (北京市环境保护监测中心)"
      },
      {
        "url": "http://beijing.usembassy-china.org.cn/070109air.html",
        "name": "U.S Embassy Beijing Air Quality Monitor (美国驻北京大使馆空气质量监测)"
      }
    ]
{
  "status": "ok",
  "data": {
    "aqi": 28,
    "idx": 5722,
    "attributions": [
      {
        "url": "http://www.airparif.asso.fr/",
        "name": "AirParif - Association de surveillance de la qualité de l'air en Île-de-France"
      }
    ]

Answer №1

To consolidate all responses with identical attributes, your best option is to compile them into an array.

Utilizing $q allows you to synchronize the promises of $http and combine them using the map function.

var promises = cityArr.map(function(name) {
    return $http.get("http://api.waqi.info/feed/" + name + "/?token=5336bd836b9ec064f6c6fe0bf7e2781838c15c87");
});  // Generate an array of Promises for each City Name.

// Wait for all Promises to resolve.
$q.all(promises).then(function(data) {
    // Extract the data attribute from each response and compile it into an array.
    var results = data.map(function(result) {
        return result.data;
    });

    console.log(results);
});

Make sure to include $q as a dependency in your controller or component.

An example has been set up on JSBin: http://jsbin.com/gukusot/edit?js,console

Answer №2

When working with JSON data, it is important to avoid duplicated key definitions.

{
    "status": "ok",
    "status": "not ok"
}

This practice should be avoided as it can lead to confusion.

To organize your JSON replies effectively, each reply should be wrapped in an object and then concatenated into a single array.


    var myApp = angular.module('myApp',[]);

    function MyCtrl($scope, $http) {
    var cityArr = ["London", "Beijing", "Paris", "New York", "Seoul", "HongKong"];
    $scope.newData = {};

    angular.forEach(cityArr, function(value) {
    var newUrl = "http://api.waqi.info/feed/" + value + "/?token=5336bd836b9ec064f6c6fe0bf7e2781838c15c87";
        $http({
            method: "GET",
            url: newUrl
        }).then(function mySucces(response) {
            $scope.newData[value] = response.data;
            console.log($scope.newData);
        }, function myError(response) {
            $scope.newData[value] = response.statusText;
        });
    });
}

The desired result should look like this:


    [
    "London": {"status": "ok", ...},
    "Beijing": {"status": ... , ... },
    ...
    ]

Some additional notes:

  1. Avoid polluting the global scope by using the var keyword for loop variables.
  2. Consider using built-in functions like angular.forEach to iterate over arrays efficiently.

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

Exploring the differences between scoping with let and without any scoping in

Within my code, there is a forEach loop containing a nested for loop. It's interesting that, even though I have a statement word = foo outside of the for loop but still inside the forEach loop, I can actually log the value of word after the entire for ...

What is the best way to incorporate multiple functions into a single ng-change event in Angular

Is it possible to add multiple functions in ng-change directive? Here is an example code snippet: <div class="col-md-2"> <select id="sel2" ng-model="updateUser.user.state" name="state" ng-change="change(); updateUser.user.city=' ...

Error: JSON expected a 'STRING' value but received something else

[ { votes: "3449", title: "The Martian | Official Trailer [HD] | 20th Century FOX", post_url: "https://www.youtube.com/watch?v=Ue4PCI0NamI", inner_url: "https://www.reddit.com/r/movies/comments/390vcp/the_martian_officia ...

What is the best way to retrieve the duration of an object tag using JavaScript or jQuery?

My goal is to determine the duration and length of only mp4 type videos. Although I used the video tag to retrieve these values, it does not support mp4 files. Despite several attempts, I was unable to get the video tag to play only mp4 files, as it stric ...

Managing the triggering of the automatic transition in view models

My question is straightforward and requires no elaborate explanation. Can Durandal be configured to control the use of transitions when transitioning between viewmodels? The motivation behind wanting to disable the animation is as follows: I have a sear ...

What is the significance of using pure reducers in the context of Redux?

Reducers that are free from side effects allow for features like time-traveling and simplify understanding of application behavior. Although it seems logical to me, I struggle to explain the specific reasons why pure reducers result in these beneficial no ...

Preventing a hyperlink from following its destination path

Hey there, I'm having trouble preventing a link from carrying out its default action. Here's the code I'm using: $("a.delete").on("click", function (e) { var container = $("#lightbox-background"); var lightbox = $("#lightbox"); ...

Using React.js to select and change the color of an element

I'm developing a movie theater app, in which I am building a feature to select seats in the cinema hall and add them to the cart. Here is the function that displays the cinema hall: export default function CinemaHall(props) { const row = props.row ...

The dual roles of Rust in managing JSON serialization duties

Exploring the realm of Json serialization in Rust has been quite enlightening. In particular, I am currently focused on how to efficiently serialize Rust objects into Json format. After delving into this topic, I have identified three distinct methods for ...

Using AJAX requests and $watch in AngularJS purposes

When a button is clicked, I want to dynamically generate a select menu. Using an ajax call, I retrieve JSON data from an external file upon the button click event. However, the select menu only updates with the JSON data after clicking the button twice. I ...

What are the differences between jQuery, jQuery Mobile, and jQuery UI?

As someone fresh to web development, I find myself overwhelmed by the numerous frameworks available. I am interested in learning about the distinctions between these frameworks and how they can benefit my projects. Additionally, I am curious as to why jQu ...

When anchor is set programmatically, the focus outline is not displayed

I am currently facing an issue with my application where I am programmatically setting focus on elements in certain scenarios. While it generally works well, I have noticed that when I set the focus on an anchor element using $("#link1").focus(), the focus ...

Leveraging viewbag information in combination with jQuery JSON techniques

I have a desire to utilize my ViewBag within a JavaScript array. After researching on using viewbag with jquery asp.net mvc 3, I believe I found the code that suits my needs: @model MyViewModel <script type="text/javascript"> var model = @Html. ...

JavaScript Array Elements Divided into Separate Arrays

I am struggling with a function that is supposed to accept an array as parameters and then log all the elements of the array into a single new array. However, the issue I am facing is that each array element is being printed separately instead of combine ...

What is the best way to manage a vuex dispatch response?

Despite feeling like the answer is right in front of me, I'm waving the white flag and seeking suggestions. The challenge lies in my login form that submits to an AWS API and reacts to the result. The trouble starts when the handleSubmit method is tr ...

Server with minimal setup requirements

While developing my Angular projects, I rely on lite server. This tool utilizes BrowserSync for tasks such as serving the site to localhost and enabling live reload functionality. In my project's root directory, there is a configuration file named bs ...

Assess the HTML containing v-html injection

Is there a way to inject raw HTML using Vue, especially when the HTML contains Vue markup that needs to be evaluated? Consider the following example where HTML is rendered from a variable: <p v-html="markup"></p> { computed: { m ...

The filter function in Material UI data grid does not seem to be functioning properly when using the renderCell method

I'm currently working on a react project that includes a Data Grid. While the filter functionality works well with most fields, it seems to be having issues with the field that utilizes renderCell. Is there a way to enable filtering for the movie titl ...

jQuery form isn't submitting

I am facing an unusual issue where my form is not sending any data, yet the page (which should only display when the data is sent) is being shown. Here is the code I am using: [..] if(form == true){ var gender = $("input[@name='rgen ...

Load website once AJAX has finished

Currently, I am using an ajax call to retrieve the color scheme of my website from the database due to having multiple clients with different schemes. My goal is to ensure that the page only loads after the ajax call has completed. Despite an expected dela ...