簡體   English   中英

如何在javascript中從嵌套的JSON中獲取多個鍵?

[英]how to get multiple keys from nested JSON in javascript?

我的JSON就像:

{
  "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
          }
        ]
      }
    }
  ]
}

我希望得到計數值以圖形顯示。 正如您在上面的json中所看到的,內部主題有兩個鍵,即TheftCrimeTheme和BurglaryCrimeTheme。 我想在everycrimeheme中獲得數值。 為此,我做了以下代碼:

 $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);
                    }

    });

我的議程是繪制圖表顯示每年的數量。要實現這一點,首先我必須得到多個鍵,如TheftCrimeTheme,BurglaryCrimeTheme等。然后我可以訪問個人值的計數值。 當我使用Object.keys()方法時,當我控制nameR的值時,我得到一個錯誤“undefined”。 請建議我怎么做?

此函數接收info (作為整個json), theme作為您想要計數的主題(即: "BurglaryCrimeTheme" )。

getThemeCrimesCount = (info, theme) => {
    const record = info.themes.find(obj => Object.keys(obj)[0] == theme)[theme];
    return record.individualValueVariable.reduce((a, b) => a += b.count, 0);
}

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

為清晰起見,將其格式化以分離元素。

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

// Parses returned JSON object.
const parseStatistics = (result) => {
  // My assumption here is that you are receiving a JSON string, which 
  // would need to be parsed into an object before being used.
  let result = JSON.parse(result);

  // Set base object
  let namR = {};

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

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

    // Set count.
    namR[type] = count;
  });

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

// Set up url info.
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";

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM