Analyzing the differences between a variable and a JSON object

In my project, I am attempting to match the selected user's gender and country with those stored in a JSON object. If the comparison yields a positive result, I want to display the corresponding "Value" for that gender and country from the JSON data.

JS:

var app = angular.module('deathApp', []);
app.controller('data', function ($scope, $http) {
    $http.get("angular/death/data.json")
        .success(function (response) {

        $scope.ages = response.fact;
        //Extract their age at death
        //Retain their gender and country information
        var gender = $('select[name=gender]').val();
        var country = $('select[name=country]').val();
        console.log("GENDER:" + gender + "." + "COUNTRY:" + country);
        //Retrieve their age at death

        if (gender && country === gender and country from $scope.ages) {
            console.log(this.$scope.ages['Value'])
        }

json:

{
    "fact": [
        {
            "COUNTRY": "Afghanistan",
            "SEX": "Female",
            "Value": "62"
        },
        {
            "COUNTRY": "Afghanistan",
            "SEX": "Male",
            "Value": "61"
        },
        {
            "COUNTRY": "Albania",
            "SEX": "Female",
            "Value": "76"
        },
        {
            "COUNTRY": "Albania",
            "SEX": "Male",
            "Value": "73"
        },
        {
            "COUNTRY": "Algeria",
            "SEX": "Female",
            "Value": "74"
        },
        {
            "COUNTRY": "Algeria",
            "SEX": "Male",
            "Value": "70"
        }
    ]
}

I am not concerned about how the JSON data is structured, as it is functioning correctly. I can successfully access the $scope.ages data.

Answer №1

To successfully retrieve the necessary data, you must map to the data source and iterate through each object in your array:

for(let i = 0; i < $scope.ages.length; i++){
    if(gender === $scope.ages[i].SEX && country === $scope.ages[i].COUNTRY){
        console.log($scope.ages[i].Value);
    }
}

Answer №2

To efficiently find the data you need, implement a for loop and break out of it once you have the desired result.

for(var i=0; i<$scope.ages['fact'].length; i++)
    if(gender === $scope.ages['fact'][i]['SEX'] && country === $scope.ages['fact'][i]['COUNTRY']){
        console.log($scope.ages['fact'][i]['Value']);
        break;
}

It appears that the array is organized alphabetically by country. You could use a binary search approach to quickly locate the desired country and then choose between the genders available.

For a demonstration with ngModel integration for tracking selected sex and country, check out this straightforward plunker example: demo.

Answer №3

To retrieve a specific value from a set of values in JSON data, you can utilize the filter function which operates on arrays.

Below is an example code that will extract an object from the provided values:

$scope.age = $scope.ages.fact.filter(function(x) {
    return x.COUNTRY === country && x.SEX === gender;
})[0].Value; // Only display the "Value" key from the current object. Therefore, $scope.age will store the age. [0] is used as you will receive an array with one matching object based on the search criteria.

Here is a simplified representation:

(function() {
  var app = angular.module("deathApp", []);

  app.controller("data", ["$scope",
    function($scope) {
      $scope.ages = {
        "fact": [{
          "COUNTRY": "Afghanistan",
          "SEX": "Female",
          "Value": "62"
        }, {
          "COUNTRY": "Afghanistan",
          "SEX": "Male",
          "Value": "61"
        }, {
          "COUNTRY": "Albania",
          "SEX": "Female",
          "Value": "76"
        }, {
          "COUNTRY": "Albania",
          "SEX": "Male",
          "Value": "73"
        }, {
          "COUNTRY": "Algeria",
          "SEX": "Female",
          "Value": "74"
        }, {
          "COUNTRY": "Algeria",
          "SEX": "Male",
          "Value": "70"
        }]
      };

      $scope.compare = function() {
        var gender = $('select[name=gender]').val();
        var country = $('select[name=country]').val();

        $scope.age = $scope.ages.fact.filter(function(x) {
          return x.COUNTRY === country && x.SEX === gender;
        })[0].Value;
      };
    }
  ]);
})();
<html data-ng-app="deathApp">

<head>
  <meta charset="utf-8" />
  <title></title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

</head>

<body data-ng-controller="data">
  <select name="gender">
    <option value="Male">Male</option>
    <option value="Female">Female</option>
  </select>
  <select name="country">
    <option value="Albania">Albania</option>
    <option value="Afghanistan">Afghanistan</option>
  </select>
  <button data-ng-click="compare()">Compare</button>
  <br />Age: {{age}}
</body>

</html>

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

Begin using datatables with the xp:table component

Within an XPage, there is a table component: <xp:table id="tblProposals"> I am looking to apply the datatables plugin to this table using a scriptblock component: <xp:scriptBlock id="scriptInitProposals"> < ...

Guide on how to decode a JSON file using UTF-8 in Swift 3/4

I've been struggling for a while to properly decode a JSON file containing Danish characters in Xcode using Swift 3 and 4. Everything works smoothly until it encounters Danish letters such as å, ø, and å. Here's the snippet of my code: let my ...

Node.js: Array remains undefined despite being logged on the console

My goal is to download a CSV file, read it line by line, and add the split lines (based on ',') to the tmparray. This code successfully prints all the elements in the array. var request = require('request'); var fs = require('fs&a ...

Does Highchart offer support for drilling down into sub-categories?

I want to implement a sub-sub drill down feature in my Chart using the following code snippet. // Create the chart Highcharts.chart('container', { chart: { type: 'column' }, title: { text: 'Highcharts m ...

Ways to extract the variable value from two asynchronous functions

I need to create a script that generates live currency conversion rates for a given array of currencies. For example, if the array is ['USD','AUD','GBP'], I want the script to calculate conversions like USD->AUD, USD->GB ...

Instructions for extracting the href value from an anchor tag using JavaScript within a specified string

How can I retrieve the href value of the last anchor tag in the provided content string using pure JavaScript, excluding jQuery? var contents = '<div id="content"><a href="http://www.okhype.com/wp-content/uploads/2016/12/ruffcoin-made-in-aba ...

Express Producing Empty Axios Post Request Body

I am facing an issue with sending two text data pieces from my React frontend to an Express backend. Whenever I use the post command with Axios, the body appears as {} in the backend and becomes unusable. Below is the code that I am using. Client (App.js) ...

Starting the Android System Magnifier with a Click: A Step-by-Step Guide

Is there a way to incorporate a magnifying glass into an HTML page using jQuery or within an Android app? Ideally, it would be for a single picture. In my application, I am displaying an HTML file from my assets in a webview. The HTML page utilizes jQuery ...

Troubleshooting NodeJS and Express: Issue accessing a function located outside a folder

I'm having trouble accessing the function I exported in app.js Here is the code snippet from app.js: function getConnection() { return mysql.createPool({ host: 'localhost', user: 'root', password: &apo ...

Sharing results between promises in AngularJSIn AngularJS, learn how to

I am currently making a GET request to my server, retrieving the response, and storing the value within a $scope.productId userService.get(true) .then(function(res) { $scope.productId = res.user.productid; } }); Next, I need to util ...

What steps can I take to successfully integrate Facebook authentication into my MEAN application while avoiding CORS issues?

Currently, I am working on a project involving the full MEAN stack. I have built a login page with a Facebook signup option in order to display a user profile page. However, I have encountered some issues along the way. To address this, I decided to create ...

The JSON response on Android is simply a string value

I have mastered the art of accessing JSON data. Recently, I received a JSON response that looks like this: "2014-02-16T20:27:54+00:00" This particular response is not in JSONArray format and does not have a name associated with it. How can I effectively ...

Error: To activate Bootstrap's dropdowns on button groups, Popper.js must be installed and configured correctly

I utilized this code within my MVC application: <div class="btn-group" role="group"> <button id="btnGroupDrop1" type="button" class="btn btn-secondary dropdown-toggle" data-toggle="dropdown ...

Displaying Values/Marks in a Unique Order with Material-UI Slider Component

The default behavior of the Material-UI slider is to display marks/values in ascending order from min to max For instance, if you have a slider configured like this: const marks = [ { value: 1, label: '1' }, { value: 2, lab ...

Exploring further into my http request reveals that the necessary data is not being displayed on the view

Expanding on the previous query (Http request in service successful but not able to show in view), I am aiming to delve deeper into my HTTP request to make an API call for a selected movie as follows: http.get('https://api.themoviedb.org/3/movie/&apo ...

PHP Loop News/Image Slider with Clickable Interval Reset and Improved Unique ID Formatting

Currently, I am in the process of setting up a news/image slider on my website using JavaScript. I have the slide data coming through a PHP loop with unique IDs, which is functioning smoothly. However, I am struggling to figure out how to reset the timer/i ...

Having trouble executing JavaScript upon form submission

Attempting to implement form validation on an email reset page. Here is the code I have written: <!DOCTYPE html> <html> <head> <title> form validation </title> <script> function validateForm ...

A guide on transferring JSON information via a POST request with C#

Looking to send JSON data in a POST request using C#? I've experimented with a few methods but encountered numerous challenges. I'm trying to make the request with a raw JSON string as well as JSON data from a separate file. How would one go ab ...

Expanding a dropdown list on the fly using vanilla JavaScript

I am restricted to using Vanilla JavaScript only, without any additional libraries like jQuery. Initially, I attempted to store all registered items in a global array and then use a forEach loop to append an <option> child to the <select>. How ...

Encountering JSON parsing errors while using fetch() POST requests in Express

Currently, I am experimenting with HTTP requests and my main focus is on sending a POST request. The data for this request is coming from an input field and I am using fetch() to send it to a URL on my local host which is set up with express. My goal is to ...