Ways to extract data from a double array JSON using AngularJS

I am dealing with a JSON file that contains 2 arrays holding some data which I need to retrieve for my AngularJS website. My aim is to extract a single object from these 2 arrays.

JSON data

[
  {
    "DailyForecasts": [
      {
        "key": "32.48,44.46",
        "class": "forecast",
        "validDate": 1484236800,
        "maxTemp": 17,
        "minTemp": 3,
        "precip_type": "rain",
        "day": {
          "humid": 34,
          "wSpeed": 20,
          "wDir": 297,
          "pop": 0,
          "uv": 2,
          "icon": 34,
          "wDirText": "غرب-شمال غ",
          "phrase": "مشمس بصورة كلية",
          "bluntPhrase": "",
          "precip_type": "rain",
          "snwAccumPhrase": "",
          "snwAccumPhraseTerse": "",
          "extQual": "",
          "weatherCode": "3400"
        },
        "night": {
          "humid": 64,
          "wSpeed": 20,
          "wDir": 297,
          "pop": 0,
          "uv": 0,
          "icon": 33,
          "wDirText": "غرب-شمال غ",
          "phrase": "صافي بصورة كلية",
          "bluntPhrase": "",
          "precip_type": "precip",
          "snwAccumPhrase": "",
          "snwAccumPhraseTerse": "",
          "extQual": "",
          "weatherCode": "3300"
        }
      },
      {
        "key": "32.48,44.46",
        "class": "forecast",
        "validDate": 1484323200,
        "maxTemp": 17,
        "minTemp": 5,
        "precip_type": "rain",
        "day": {
          "humid": 48,
          "wSpeed": 14,
          "wDir": 287,
          "pop": 0,
          "uv": 3,
          "icon": 32,
          "wDirText": "غرب-شمال غ",
          "phrase": "مشمس",
          "bluntPhrase": "",
          "precip_type": "rain",
          "snwAccumPhrase": "",
          "snwAccumPhraseTerse": "",
          "extQual": "",
          "weatherCode": "3200"
        },
        "night": {
          "humid": 67,
          "wSpeed": 14,
          "wDir": 287,
          "pop": 10,
          "uv": 0,
          "icon": 31,
          "wDirText": "غرب-شمال غ",
          "phrase": "صافي",
          "bluntPhrase": "",
          "precip_type": "rain",
          "snwAccumPhrase": "",
          "snwAccumPhraseTerse": "",
          "extQual": "",
          "weatherCode": "3100"
        }
      }
    ]
  }
]

Controller Code

 app.controller('Hillahctlr', function($scope, $http, wind, arrivecss, windname, icons) {
     $scope.wind_dir = wind;
     $scope.icons = icons;
     $scope.arrivecss = arrivecss;
     $scope.windname = windname;
     var service_url = "/key=e88d1560-a740-102c-bafd-001321203584&units=m&locale=ar&cb=JSON_CALLBACK";
     $http.jsonp(service_url)
         .success(
             function(data) {
                 console.log(data);
                 yData = data.HourlyForecasts;
                 $scope.ali = [];
                 for (var i = 0; i < 9; i++)
                 {
                     $scope.ali[i] = {
                         dayes: yData[i].temp,
                     };
                 }
             })
 })
 }

I tried looping inside this array using ng-repeat, but unfortunately it's not working as expected. Here is the code:

HTML

<div class="ForecastArea-Day Last weatherteble" ng-repeat="alis in dayes">
   {{alis.dayes}}
</div>

An error message stating Error: yData is not defined keeps popping up. Any assistance would be greatly appreciated.

Answer №1

Implement yData = data[0].HourlyForecasts;. The JSON commences with [ { "DailyForecasts": [ indicating that it is an array of objects.


It is working perfectly, thank you. What about the object day inside HourlyForecasts? When I execute yData[i].day, it returns undefined.

Please review my snippet below:

yday = data[0].DailyForecasts;
$scope.daily = [];
for(var i=0; i<9; i++) {
    $scope.daily[i] = {maxTemp: yData[i].maxTemp,
                       minTemp: yData[i].minTemp,
                       validDate: yData[i].validDate,
                       icon: yData[i]day.icon, };
}

The issue seems to be a missing dot ".":

                   //    icon: yData[i]day.icon, };
                       icon: yData[i].day.icon, };
                   //                ^ --- insert a dot here

Additionally, ensure you declare yday as a variable:

 //yday = data[0].DailyForecasts;
 var yday = data[0].DailyForecasts;

Failure to use var declaration may lead to global namespace pollution.

Answer №2

Give this a shot.

let elements = [];

 elements = {events: eventData[i].details,};
 $scope.elements = elements;

<div class="Event-Day Last eventTable" ng-repeat="elements in element.events">
{{element.event}}
</div>

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

I am searching for a regular expression in JavaScript that can detect balanced parentheses within a phone number. The pattern I currently have is /^([1]{0,1})s?(?d{3})?[-s]?d{3}[-s]?d{

When entering a phone number, the following format must be followed: The phone number may start with a "1," which is optional. There can be a space after the starting digit, which is also optional. An opening parenthesis "(" is optional. This should be fo ...

The global variable is inaccessible when invoked within a dynamically generated function

The variable selected is a global one and accessed using this.selected, which reliably returns the correct value. However, when called from a dynamically created function, it returns unknown. onClick: function(val){ for (i = 0; i < positi ...

Creating an Angular search input and connecting it to an API: A step-by-step guide

As someone who is new to Angular, I have been exploring the functionality of an API that handles server-side filters. After successfully testing it using Postman, I decided to implement a search box to perform the filtering directly from the user interface ...

What is the best way to prevent the onClick event from triggering during the page rendering process?

I am currently working with React, Gatsby, and Material UI Buttons. I'm facing an issue where the most recently pressed button is getting disabled along with all other buttons when running my code. Despite already implementing bindings, as suggested b ...

Utilizing Github Pages as an API, understanding the concept of rate limiting

I am currently developing an Android app with an expected user base of around 1-2k per day. My requirement is a JSON file hosted at . Are there any restrictions to consider when hosting this file? Are there more efficient methods for hosting the JSON to s ...

What is the best way to display output within an array using PHP?

After creating a hashmap array, I utilized a foreach loop to generate output. The current output is dog@ant dogant antdog <?php $rule = [ "c" => "d", "a" => "o", "t" => "g", "h" => "a", "1" => "@", "e" => "n", "n" => "t" ]; $orde ...

After utilizing the function, the forward and back arrows are no longer visible

After setting up my slideshow, I encountered an issue where clicking the next or previous buttons caused them to shrink down and turn into small grey boxes. Has anyone experienced this before? This relates to PHP/HTML if ($_SERVER['REQUEST_METHOD&ap ...

Python Selenium : Struggling to locate element using ID "principal"

As part of my daily work, I am currently working on developing a Python Script that can automate the process of filling out forms on various websites. However, I encountered an issue with Selenium while trying to interact with certain types of webforms. F ...

Access denied - you shall not pass!

Encountering an Access Denied Error on https in Internet Explorer while trying to make an ajax call to my server1. The response from the server1 contains another ajax call, but my ajax call URL is on http. I have tried implementing CORS and JSONP, but it ...

Using an if/else statement to detect if the iFrame is devoid of content

I have a customized youtube video section on my website template that can display either an embedded video or an image based on client preference. Currently, I am trying to implement code that will detect if the youtube video source is empty and then displ ...

Error: Mocha Scope Function Undefined

Currently, I am following some TTD tutorials with Javascript and facing what appears to be a Javascript issue rather than a TTD problem. Here are the tests I have: 'use strict'; var chai = require('chai'); var expect = chai.expect; va ...

Contrary to expectations, the middleware EJS fails to render JPG files at

I am currently working on a NodeJS server using EJS. The goal of this server is to render an HTML page that contains a line of text and a jpg file. However, I am encountering an issue with the jpg file not being loaded by the server. Even though I have sp ...

Unable to retrieve the saved user from the Express.js session

Below is the code in question: app.post('/api/command', function (req, res, next) { var clientCommand = req.body.command; console.log("ClientCommand: ", clientCommand); if (!req.session.step || req.session.step === EMAIL) { ...

Employing Modernizer.js to automatically redirect users to a compatible page if drag and drop functionality is not supported

I recently set up modernizer.js to check if a page supports drag and drop functionality. Initially, I had it set up so that one div would display if drag and drop was supported, and another div would show if it wasn't. However, I ran into issues with ...

How can I assign the ng-repeat property as the ng-model?

Within my view, there is a select box available for selecting a worker. <select ng-model="search.wrk_worker_id"> <option ng-repeat="w in workers.message">{{w.wrk_forename}}</option> </select> w possesses the following properti ...

ng-include once the application has finished loading

Currently, my server is using handlebars to generate the initial HTML page. I would like to include a ng-include in this page to dynamically update the client side. However, every time my application runs, it loads the page and the data-ng-include="templa ...

Activate a function when clicking on a Bootstrap toggle switch (checkbox)

Is it possible to have the function updateText() executed when I click on the checkbox with the id text_mode? I attempted using onClick="updateText()", but it didn't yield the desired outcome. While searching for solutions, I noticed that many respons ...

"Utilizing 3 tabs with a single controller, each having distinct parameters

My current challenge involves: a) I have a template titled EventsGraph.html, which consists of 3 tabs: A/B/C. b) Additionally, there is a controller named EventsGraphCtrl.js. The primary task of EventsGraph.js is to populate chart objects using Google Ch ...

Creating a REST Client Application (Post) to Connect with a Web API

I've been encountering some difficulties while attempting to retrieve the results of a POST operation from a Web Service. While testing the API Services using a chrome extension, everything works fine there. However, I'm facing challenges when it ...

A guide to integrating Material-UI with your Meteor/React application

I encountered an issue while trying to implement the LeftNav Menu from the Material-UI example. The error message I received is as follows: While building for web.browser: imports/ui/App.jsx:14:2: /imports/ui/App.jsx: Missing class properties transf ...