在使用forEach循环遍历数组时,无法从JSON对象获取值

时间:2018-03-07 08:13:00

标签: javascript arrays json loops foreach

我正在迭代一个带有forEach循环的数组,每次我得到一个JSON对象,每次我想从JSON对象中获取某些值,但不知怎的,这不起作用。 console.log(json.responseJSON)始终返回undefined

代码如下所示:

searchterms = ["a", "b","c"];
searchterms.forEach(function(entry) {

    console.log(entry);

    json = $.getJSON('https://www.markerapi.com/api/v1/trademark/searchall/'+entry+'/wordcount/2/limit/20/username/XXX/password/XXX')

    console.log(json);

    console.log(json["responseJSON"])
});

数组中第一项的JSON如下所示:

responseJSON: {"count":1,"trademarks":[{"serialnumber":"71045585","wordmark":"A","code":"GS0371","description":"WRITING AND PRINTING PAPER","registrationdate":"04\/08\/1913"}]}"

后来我计划从JSON获取“wordmark”和“description”值。我该怎么做?

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

检查jquery的documentation,你需要为getJSON进行回调。请查看以下代码段。它可能对你有帮助。

searchterms = ["a", "b", "c"];
searchterms.forEach(function(entry) {
  console.log(entry);
  json = $.getJSON('https://www.markerapi.com/api/v1/trademark/searchall/' + entry + '/wordcount/2/limit/20/username/XXX/password/XXX', function(data) {
    console.log(data);
    console.log(data["responseJSON"])
  });
});