javascript - 如何获取嵌套数组中特定对象的列表?

标签 javascript jquery wikipedia-api

如果我运行这个:

var url="https://en.wikipedia.org/w/api.php?format=json&action=query&prop=categories&titles=Victory_Tests&callback=?";
$.getJSON(url,function(data){
    $.each(data, function(i, item) {
        console.log(item);
    });
});

控制台给我:

{pages: {…}}
   pages: 2347232: 
     categories: Array(8)0: 
      {ns: 14, title: "Category:Aftermath of World War II in the United Kingdom"}
      1: {ns: 14, title: "Category:All articles with unsourced statements"}
      2: {ns: 14, title: "Category:Articles with unsourced statements from August 2015"}
      3: {ns: 14, title: "Category:Articles with unsourced statements from March 2009"}
      4: {ns: 14, title: "Category:English cricket seasons from 1919 to 1945"}
      5: {ns: 14, title: "Category:History of Test cricket"}
      6: {ns: 14, title: "Category:Use British English from September 2011"}
      7: {ns: 14, title: "Category:Use dmy dates from September 2011"}
      length: 8
      __proto__: Array(0)
      ns: 0
      pageid: 2347232
      title: "Victory Tests"
    __proto__: 
  Object__proto__: 
 Object__proto__: Object

我需要获取所有类别

我尝试了item.categories

data.parse.pages.map(function(val){ 
    return val.categories[0]; 
}));

但是这是不对的

最佳答案

您可能应该获得多个页面,如果您想聚合所有内容,请执行以下操作:

 var url="https://en.wikipedia.org/w/api.php?format=json&action=query&prop=categories&titles=Victory_Tests&callback=?";
$.getJSON(url,function(data){
    var categories = Object.values(data.query.pages).map( (i) => i.categories.map( (c) => c.title) );
    console.log(categories);
});

关于javascript - 如何获取嵌套数组中特定对象的列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45533421/

相关文章:

javascript - 无法使用 Wikipedia API 调用获取随机 JSON 对象属性

javascript - 如何从原始 HTML 响应中删除某些元素类型?

javascript - ng-repeat 上的嵌入

javascript - 编写一个javascript来显示存入金额的面额

javascript - 为同一页面上的两个独立画廊使用灯箱画廊代码?

jquery - 为什么我不能用 animate 打开/关闭多个 div?

javascript - 使用他们的 API 构建维基百科查看器,总是出现错误

javascript - 我不能在我的数组中使用 .push 和 Angular 吗?无法读取未定义的属性 jsonArr

javascript - Angular- 如何重复具有不同数据的组件?

jquery - 将 addDomListener 与 googlemaps 一起使用不起作用