Tips for extracting multiple keys from deeply nested JSON structures in Javascript:

My JSON structure is:

{
  "boundaries": [
    {
      "boundary": {
        "boundaryId": "45083021141",
        "boundaryType": "USA_POSTCODE",
        "boundaryRef": "B1"
      }
    }
  ],
  "themes": [
    {
      "TheftCrimeTheme": {
        "boundaryRef": "B1",
        "individualValueVariable": [
          {
            "name": "2013 Theft Crime",
            "description": "Theft Crime for 2013",
            "count": 2080
          }
        ]
      }
    },
    {
      "BurglaryCrimeTheme": {
        "boundaryRef": "B1",
        "individualValueVariable": [
          {
            "name": "2013 Burglary Crime",
            "description": "Burglary Crime for 2013",
            "count": 302
          }
        ]
      }
    }
  ]
}

I am looking to extract the count value to display in a graph. The JSON data consists of two themes: TheftCrimeTheme and BurglaryCrimeTheme. I want to retrieve the count value for each crime theme. Here is the code I tried:

 $http.get("http://152.144.218.70:8080/USACrime/api/crimeAPI?city="+$scope.strCity+"&crimeType="+$scope.type1+"&years="+$scope.type+"&month="+$scope.type2).success(function (result) {  
   for(var i=0;i<result.themes.length;i++){
                      var crime={};
                        console.log("did",result.themes[i]);
                      var test2 = result.themes[i];
                      console.log("test2",test2);
                      var test = test2[Object.keys(test2)];
                      console.log("test",test);
                      crime.name = Object.keys(result.themes[i]);
                      console.log("CrimeName",crime.name);
                      crime.data = [];
                      var test1 = test.individualValueVariable[0].count;
                      console.log("test1",test1);
                      crime.data.push(test1);
                      crime_data.push(crime);
                    }

    });

My goal is to create a graph displaying the count for each year. To achieve this, I need to access multiple keys like TheftCrimeTheme, BurglaryCrimeTheme, etc., and then extract the count value from individualValueVariable. When trying to use the Object.keys() method, I encountered an error stating "undefined" when logging the values of nameR. Any suggestions on how to resolve this issue?

Answer №1

In the following function, info represents the entire JSON data, and theme is the specific theme for which you want to retrieve the count (e.g., "BurglaryCrimeTheme").

calculateThemeCrimes = (info, theme) => {
    const selectedThemeRecord = info.themes.find(obj => Object.keys(obj)[0] == theme)[theme];
    return selectedThemeRecord.individualValueVariable.reduce((accumulator, currentValue) => accumulator += currentValue.count, 0);
}

calculateThemeCrimes(info, "BurglaryCrimeTheme"); // 302
calculateThemeCrimes(info, "TheftCrimeTheme"); // 2080

Answer №2

Breaking down the elements for better understanding.

// This function constructs a URL with query string parameters.
const buildURL = (uri, params) => {
  let queryParams = Object.keys(params).map(function(k) {
      return encodeURIComponent(k) + '=' + encodeURIComponent(params[k])
  }).join('&');
  return uri + '?' + queryParams;
};

// This function parses a JSON object received as a parameter.
const parseStatistics = (result) => {
  // Here, we assume that the input is a JSON string that needs to be parsed into an object first.
  let result = JSON.parse(result);

  // Initialize base object
  let namR = {};

  // Loop through themes array
  result.themes.forEach(function(element) {
    // Find the name of the current theme
    let type = Object.keys(element)[0];

    // Get count for the current theme
    let count = element[type].individualValueVariable.count;

    // Assign the count
    namR[type] = count;
  });

  // Log the object
  console.log(namR);
};

// Define parameters for the URL
let params = {
  city: $scope.strCity,
  crimeType: $scope.type1,
  years: $scope.type,
  month: $scope.type2
};
let baseURL = "http://152.144.218.70:8080/USACrime/api/crimeAPI";

// Make the HTTP request  
$http.get(buildURL(baseURL, params)).success(parseStatistics(response));

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

JS, Async (library), Express. Issue with response() function not functioning properly within an async context

After completing some asynchronous operations using Async.waterfall([], cb), I attempted to call res(). Unfortunately, it appears that the req/res objects are not accessible in that scope. Instead, I have to call them from my callback function cb. functio ...

Generating a JSON entity

When using Java, I am making a JSON request to the server with the following parameters. {method:'SearchBySearchConfiguration', params:[{SearchCriteria:'%arriva', IsAccountSearch:true, IsContactSearch:false, SearchByName:true, SearchB ...

Odd behavior observed while running npm scripts in the npm terminal

Included in my package.json file are the following dependencies: "devDependencies": { "chromedriver": "^2.37.0", "geckodriver": "^1.11.0", "nightwatch": "^0.9.20", "selenium-server": "^3.11.0" }, "scripts": { "e2e": "nightwatch -c test ...

Emphasize Expandable Sections based on Search Term

I have been working on developing an HTML page for my company that will showcase a list of contacts in an "experts list". Currently, the list is structured using collapsible DIVs nested within each other. Additionally, the HTML page features a search func ...

Casting types of objects in Angular2 using TypeScript

Trying to extract the model object from the JSON obtained through a http response call. The following JSON represents the body of the http response, { "dataType": "RWSupplier", "partyName": "Lifecare Pharmaceuticals", "partyShortName": null, "partySecon ...

How to achieve a typewriter effect in React using JavaScript

I've been attempting to incorporate a typewriter effect into my website - at the moment, the animation is functioning but each letter appears twice (e.g. instead of reading "Welcome!" it displays "Wweellccoommee!!"). I suspect this is an asynchronous ...

Individual User's Time Slot

Greetings! I am in the process of developing a web application where users can seek assistance for their problems: One challenge I am facing is how to inform users of the time a question was posted in their specific time zones. For instance, if I post a ...

How to Watch a Video from Local Storage in Angular

I am currently developing a small Angular application that allows users to view a collection of videos saved locally. The goal is for users to be able to save this collection in order to revisit these videos at a later time. The paths of the videos are sto ...

Transforming JSON objects into Dataframes

I'm looking for more efficient ways to convert JSON objects to DataFrames. When I loop through 2 rows of my input_df, I get 2 JSON objects printed in suggestion_string. Here is the expected output data frame structure: https://i.sstatic.net/bCnqR.png ...

Converting JavaScript JSON into a PHP array

When working with Javascript, I create an array using the following code: cachePHP = "'lat':'" + (Number(upDataItems[2])).toFixed(5)+"'"; cachePHP = cachePHP + ",'lon':'" + (Number(upDataItems[3])).toFixed(5)+"' ...

Obtaining values from a JSON String in Android: A comprehensive guide

In my Android application, I am currently working with a JSON string that looks like this: [{"tel1":"999","tel2":"0790000000","tel3":"","interval":"60","deleteLocal":"1","id":"2"}] Can someone guide me on how to efficiently parse this JSON string into a ...

Transferring user input data from Angular 2 to Slim PHP endpoint

Help needed with parsing form-data in Slim PHP. How can I put form-data into an array in Slim PHP? I have tried different methods but the data always gets kicked out in one array with no specific way to target the form data. Any suggestions would be helpf ...

"Use jQuery to select all the cells in a row except for the

I found a visually appealing table layout that looks like this : https://i.stack.imgur.com/oRxYP.png What caught my attention is how clicking on a row selects the entire row. Take the example in the image above, where the second row is highlighted upon s ...

The div's width shifts upon reaching the top of the page

Creating a blog site example and trying to lock the position of a div once it reaches the top of the page. Utilizing materialize.css for this task. <div class="row"> <div class="col m8 s12"> <!-- content goes here --> < ...

Iterate over rows in a b-table component in Vue

In the context of Vue bootstrap, a b-table consists of a list with an unknown number of rows. The requirement is to display a remove button only if the email in the row matches that of the currently logged-in user. This functionality currently works for a ...

Getting the result from a callback function in TypeScript

In my Typescript file Service.ts, I have a function called doCallAuth: export const doCallAuth = (username, password) => { var auth = new Auth({ url: '...', }); var status; auth.authenticate(username, password ...

What could be the reason for this code returning a "module not found" error?

Within localbase.js... const fs = require("fs"); if(!fs.existsSync(__dirname + "/localbase.json")) fs.writeFileSync("./localbase.json", "{}"); let database = require("./localbase.json"); The code abov ...

Encountered errors while trying to install ng-bootstrap, installation of package was unsuccessful

I am currently developing an Angular application and I require an accordion component for it. My efforts to install the ng-bootstrap package using the command 'ng add @ng-bootstrap/ng-bootstrap' have been unsuccessful as the installation fails ev ...

When jQuery is used to move rows between tables, it can interfere with

When moving rows between tables, everything seems to work fine. However, once the row is moved to the other table, all JavaScript functions related to that row stop working, and the reason remains unknown. The JavaScript code is simple - it involves takin ...

What methods can be used to prefill formatted HTML content when launching an email client?

My first step is to generate the formatted html code: onClick={(_) => { const content = `Check out what I found ..<div></div`; Next, I set the content variable window.location.href = `mailto:<a href="/cdn-cgi/l/email-protection" cla ...