Struggling to iterate over key-value pairs in a JSON object?

I am currently working with AngularJS and have successfully retrieved exchange rates from fixer.io. However, I am facing difficulties in extracting both the country and rate data by looping through the key-value pairs. At the moment, I can only access the rate and I also need the country information. Can anyone pinpoint what I may be missing in my code? Below is a snippet showcasing how the rates are displayed on the fixer.io website.

HTML5

<div ng-controller="AngularJSCtrl">
    <ul ng-repeat="x in data.rates">
        <li>{{ x }}</li>
    </ul>
  </div>

JS

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

myApp.service('dataService', function($http) {
    delete $http.defaults.headers.common['X-Requested-With'];
    this.getData = function(callbackFunc) {
        $http({
            method: 'GET',
            url: 'http://api.fixer.io/latest',
            params: 'limit=10, sort_by=created:desc',
            headers: {'Authorization': 'Token token=xxxxYYYYZzzz'}
        }).success(function(data){
            // With the data succesfully returned, call our callback
            callbackFunc(data);
        }).error(function(){
            alert("error");
        });
     }
});

myApp.controller('AngularJSCtrl', function($scope, dataService) {
    $scope.data = null;
    dataService.getData(function(dataResponse) {
        $scope.data = dataResponse;
    });
});

Rates as displayed on the website

{
    "base": "EUR",
    "date": "2016-09-20",
    "rates": {
        "AUD": 1.4812,
        "BGN": 1.9558,
        "BRL": 3.6473,
        "CAD": 1.4792,
        "CHF": 1.0943,
        "CNY": 7.4604,
        "CZK": 27.022,
        "DKK": 7.452,
        "GBP": 0.86213,
        "HKD": 8.6753,
        "HRK": 7.5127,
        "HUF": 309.12,
        "IDR": 14698.01,
        "ILS": 4.2231,
        "INR": 74.962,
        "JPY": 113.93,
        "KRW": 1252.4,
        "MXN": 21.965,
        "MYR": 4.631,
        "NOK": 9.2648,
        "NZD": 1.522,
        "PHP": 53.527,
        "PLN": 4.2975,
        "RON": 4.4513,
        "RUB": 72.5141,
        "SEK": 9.5763,
        "SGD": 1.5237,
        "THB": 38.909,
        "TRY": 3.3275,
        "USD": 1.1184,
        "ZAR": 15.5144
    }
}

Answer №1

Similar to the other responses, here is a demonstration with a live example.

angular.module('app',[])
.controller('MyCtrl', function($scope){
$scope.data = 
{
    "base": "EUR",
    "date": "2016-09-20",
    "rates": {
        "AUD": 1.4812,
        "BGN": 1.9558,
        "BRL": 3.6473,
        "CAD": 1.4792,
        "CHF": 1.0943,
        "CNY": 7.4604,
        "CZK": 27.022,
        "DKK": 7.452,
        "GBP": 0.86213,
        "HKD": 8.6753,
        "HRK": 7.5127,
        "HUF": 309.12,
        "IDR": 14698.01,
        "ILS": 4.2231,
        "INR": 74.962,
        "JPY": 113.93,
        "KRW": 1252.4,
        "MXN": 21.965,
        "MYR": 4.631,
        "NOK": 9.2648,
        "NZD": 1.522,
        "PHP": 53.527,
        "PLN": 4.2975,
        "RON": 4.4513,
        "RUB": 72.5141,
        "SEK": 9.5763,
        "SGD": 1.5237,
        "THB": 38.909,
        "TRY": 3.3275,
        "USD": 1.1184,
        "ZAR": 15.5144
    }
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>

<div ng-app="app" ng-controller="MyCtrl">
  
  <div ng-repeat="(key,value) in data.rates">
    {{key}} - {{value}}
  </div>
</div>

Answer №2

If you want to loop through object properties, you can use ngRepeat directive in AngularJS. For more information, visit ngRepeat documentation

   <div ng-controller="AngularJSCtrl">
        <ul ng-repeat="(country, rate) in data.rates">
            <li>{{ country }} - {{ rate }}</li>
        </ul>
    </div>

Answer №3

ng-repeat is a handy directive that allows you to loop through both the keys and values of an object's properties. If you have a dictionary with key-value pairs, all you need to do is modify your ng-repeat declaration like this:

<ul ng-repeat="(key, value) in data.rates">
    <li>{{key}}: {{ value }}</li>
</ul>

Answer №4

Even though the other answers correctly use ng-repeat, I believe there is a better way to structure the code. Creating a new <ul> with a single <li> for each key/value pair doesn't seem logical. Instead, you should have a single <ul> with a child <li> for each country/rate combination like this:

<ul>
    <li ng-repeat="(country, rate) in data.rates" ng-bind="country + ': ' + rate"></li>
</ul>

Additionally, it is recommended to avoid interpolation ({{ }}) whenever possible as it can slow down the page loading process, especially on slower connections. It's better to use ng-bind instead.

If you want to add some formatting to the output, you can follow this example:

var myModule = angular.module('myModule', []);
  myModule.controller("myCtrl", ["$scope", function($scope) {
    $scope.data = {
      "base": "EUR",
      "date": "2016-09-20",
      "rates": {
        "AUD": 1.4812,
        "BGN": 1.9558,
        "BRL": 3.6473,
        "CAD": 1.4792,
        ... // other country/rate pairs
      }
    }
  }]);
ul > li {
  list-style: none;
}
ul > li:nth-child(even) {
  background-color: #cecece;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myModule" ng-controller="myCtrl">
  <ul style="width: 150px;">
    <li ng-repeat="(country, rate) in data.rates">
      <span ng-bind="country + ': '"></span><span style="float: right;" ng-bind="rate | number:4"></span>
    </li>
  </ul>
</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

Ensure the initial word (or potentially all words) of a statement is in uppercase in Angular 2+

Struggling with capitalizing words in an Angular 2 template (referred to as view) led to an error in the console and the application failing to load, displaying a blank page: Error: Uncaught (in promise): Error: Template parse errors: The pipe 'c ...

Using React's useEffect to implement a mousedown event listener

I created a modal that automatically closes when the user clicks outside of it. method one - involves passing isModalOpened to update the state only if the modal is currently open. const [isModalOpened, toggleModal] = useState(false); const ref = useRef(n ...

Executing code within Vue js $set method's callback

For my v-for loop that generates a list of flights, I have implemented functionality where the user can click on a "flight details" button to send an AJAX request to the server and append new information to the results array. To update the view accordingly ...

Mastering file handling with jQuery File Upload Middleware in Node.js Express: blending files and branding with watermarks

I was successful in setting up the jquery-file-upload-middleware with express.js 4.0, but I am struggling with configuring it properly. Here is the script I used for upload: var upload = require('jquery-file-upload-middleware'); upload.configur ...

How can I efficiently remove elements from the end of an array in Vue.js?

Is there a way to splice data starting from the back with a higher index? When clicking on the .delete div, how can I make it so the .image-box div deletes starting from the end? I need help implementing this feature in my code. Here is a snippet: < ...

Setting the default typing language in Protractor: A step-by-step guide

Is there a way to specify a default typing language in my configuration file? While running test cases locally, I am unable to switch keyboard languages during execution as it impacts the typing language for Protractor causing the tests to fail. If you h ...

Creating dynamic HTML elements with bound JSON data

When a JSON array list of objects is retrieved from the database, it is sent to the client side upon page load of the current user control. var json = new JavaScriptSerializer(); var jsonList = json.Serialize(mylList); Page.Client ...

What is the proper way to add an object to an array within an object in TypeScript?

import {Schedule} from './schedule.model'; export class ScheduleService{ private schedules:Schedule[]=[ new Schedule("5:00","reading"), new Schedule("6:00","writing"), new Schedule("7:00","cleaning") ]; getSchedule(){ ret ...

What is the recommended approach for effectively cascading the deletion of a secondary object in MongoDB when an account is

My app allows users to create accounts and interact with posts by liking and sharing them. However, I'm facing an issue when a user decides to delete their account. I have managed to resolve most of the related data removal except for one specific cas ...

transforming the jquery form submission to angular

I am facing a challenge trying to convert this jquery code into Angular, and I am having trouble making it work. // jquery $('#formsubmit').click(function(ev){ ev.preventDefault(); $.ajax({ url: "/url.json", type: "POST", data: { ...

Guide on inserting text within a Toggle Switch Component using React

Is there a way to insert text inside a Switch component in ReactJS? Specifically, I'm looking to add the text EN and PT within the Switch Component. I opted not to use any libraries for this. Instead, I crafted the component solely using CSS to achie ...

Show the value of one text box inside another text box by harnessing the power of AngularJs when a

I am new to AngularJs and finding it a bit complex. I have set up two text boxes and a button. My goal is to input text into the first text box, then click the button to display that value in the second text box. I've only written a small amount of co ...

Setting an Alias for AVA Tests: A Step-by-Step Guide

I need to set up global aliases in my project without using Webpack or Babel. Currently, I am testing with AVA. The npm package module-alias allows me to define aliases in my package.json file. However, when I try to create a basic example following the d ...

The tab element is not receiving a click event in Protractor

This is the complete HTML code for the Tab section. <tab heading="Meta Data" id="heading_meta-data"> <div id="meta-data" class="row"> <div class="col-md-3 col-xs-3"> ...

transmit JSON formatted form data to an AngularJS platform

I have a webpage built on AngularJS with a login feature. I want to iframe this webpage onto my own page and automatically log in my users. Upon inspecting the AngularJS site, I noticed that the login procedure expects a json object. I have tried multipl ...

Placing miniature vessels within a larger vessel, where two small containers fit on one level of the larger container (refer to images)

I am looking for a way for users to input text in the "your text" container and then click "add". This action should create a new container within the larger red-lined container with the information provided by the user. I know how to do this already, but ...

Struggling to achieve the expected results when trying to convert a PHP array into JSON

When I receive names and links of files from an external website, I use the following code to convert them into a JSON string: <?php include('simple_html_dom.php'); $f = $_GET['f']; $w = "www.something.com"; $dom = file_get_html($w ...

Is Angularjs revolutionizing the use of service dictionaries for Dependency Injection by consolidating multiple services into one?

Despite using ng-annotate, the process of declaring and updating dependencies arrays, along with dependency injection params, is becoming tedious for me. This is especially evident in my controllers and directives. I'm wondering if it would be feasib ...

Is it common for NA values to appear in the data frame due to JSON parsing?

I recently obtained a collection of JSON files from the YELP public data challenge. These files can be found at this link: The files are in NDJSON format, and I have successfully read them using the following code: library(jsonlite) df <- stream_in(fi ...

Enzyme fails to locate text within a div even though it is present

In my current test scenario, I have a set of data displayed in Material-UI Cards. The data is provided through a JSON array consisting of objects with fields like projectName, crc, dateCreated, createdBy, and lastModified. { projectName: 'P ...