在外部JSON中搜索项目

问题描述 投票:0回答:1

我有一个JSON文件的URL,我想获取所有具有相同值的项目。示例:

[http://sampleurl.com具有此JSON

`{ 
   "posts":[ 
      { 
         "authors":[
           {
             {"name":"John",
              "age": 30
             },
             {"name":"John",
              "age": 35
             }
            }
         ]
       }
    ]
}`

[我想做的是列出所有具有相同名字的作者及其年龄。

我已经尝试过但没有成功:

`var allposts = "http://sampleurl.com";
    $.each(allposts.posts.authors, function(i, v) {
        if (v.name == "John") {
        alert("Ok");
        return;
        }
    });`

谢谢

json
1个回答
0
投票

您需要通过Ajax调用获取数据:

let authors = {};
$.get( "http://sampleurl.com" ).done(data =>
  data.posts.authors.forEach(author => {
    authors[author.name] = authors[author.name] || []
    authors[author.name].push(author)
  });
);

最后,您有一个以唯一作者姓名为关键字的对象,每个关键字都包含一个具有该姓名的作者数组作为其值。您可以进行进一步处理,以将其转换为所需的数据结构。

© www.soinside.com 2019 - 2024. All rights reserved.