简体   繁体   English

遍历JSON响应对象

[英]Loop through JSON response object

I get a response from an API like below. 我从如下所示的API得到响应。 How can I loop through the results using jQuery to access the value for 'appName' for example? 例如,如何使用jQuery访问“ appName”的值来遍历结果?

var apps = 
{ 
  358899126: 
   { appId: 358899126,
     appName: 'Tagged -Chill, Chat & Go Live!',
     primaryCategoryName: 'Social Networking' },
  359917414: 
   { appId: 359917414,
     appName: 'Solitaire',
     primaryCategoryName: 'Games' } 
}

You can use Object.keys to get the key of each object, and then use he square bracket syntax to get the actual object, like so: 您可以使用Object.keys获取每个对象的键,然后使用方括号语法获取实际的对象,如下所示:

 var apps = { 358899126: { appId: 358899126, appName: 'Tagged -Chill, Chat & Go Live!', primaryCategoryName: 'Social Networking' }, 359917414: { appId: 359917414, appName: 'Solitaire', primaryCategoryName: 'Games' } } Object.keys(apps).forEach((key) => { let obj = apps[key]; console.log(obj.appName); }); 

You need to use Object.keys to get all indexes of an object as an array and then loop through them.Try this. 您需要使用Object.keys将对象的所有索引作为数组获取,然后遍历它们。

var apps = 
{ 
  358899126: 
   { appId: 358899126,
     appName: 'Tagged -Chill, Chat & Go Live!',
     primaryCategoryName: 'Social Networking' },
  359917414: 
   { appId: 359917414,
     appName: 'Solitaire',
     primaryCategoryName: 'Games' } 
}
let k = Object.keys(apps);
for(var s = 0 ; s < k.length ; s++)
{
    console.log(apps[k[s]]['appName'];
}

Here you go with a solution 在这里你有一个解决方案

 var apps = { 358899126: { appId: 358899126, appName: 'Tagged -Chill, Chat & Go Live!', primaryCategoryName: 'Social Networking' }, 359917414: { appId: 359917414, appName: 'Solitaire', primaryCategoryName: 'Games' } } for(var k in apps){ console.log(apps[k].appName); } 

Loop will iterate through keys, for accessing the appName use the dot operator or can be done other way console.log(apps[k]["appName"]); 循环将迭代键,以便使用点运算符来访问appName或可以通过其他方式完成console.log(apps[k]["appName"]); .

Hope this will help you. 希望这会帮助你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM