从JSON数组搜索结果查询中提取动态键值

时间:2017-07-09 09:36:22

标签: javascript jquery arrays json

我使用Wikipedia API搜索Wiki文章。当我单击提交按钮时,我得到了一个JSON数组:

0 {ns: 0, title: "Help", size: 3677, wordcount: 433, snippet: "<span class=\"searchmatch\">Help</span> is any form …mmand-line shells that invokes documentations and", …}

1 {ns: 0, title: "Online help", size: 7326, wordcount: 380, snippet: "(HTML), which includes HTML <span class=\"searchmat…earchmatch\">help</span> is also provided via live", …}

2 {ns: 0, title: "Help desk", size: 9491, wordcount: 1296, snippet: "A <span class=\"searchmatch\">help</span> desk is a …ated to a company's or institution's products and", …}

...

我需要提取标题的值并在结果列表中的HTML中使用它,同时将其放在url中,以便用户可以单击结果并转到相应的页面。 (URL:http://../[title]

该数组位于data.query.search

由于结果是动态的,我可能需要某种for循环来迭代这个数组,无论有多少结果。我试过这个for循环,但它没有用。

console.log(data.query.search); //shows array in console
          data.query.search =""; //the location of JSON array
 for (i = 0; i < data.query.search["results"].length; i++) {
  data.query.search["results"][i]["title"];
  console.log("results"); 
}

我怀疑我没有正确定位数组元素,键和值。我很感激任何建议。欢呼声。

3 个答案:

答案 0 :(得分:0)

你的代码有一些奇怪的东西。首先,你是&#34;清算&#34;第二行data.query.search。其次,在循环中,您不能将每个结果的title分配给任何变量,只需打印&#34;结果&#34;。第三,您说数组在data.query.search,但您尝试访问属性results。您可以尝试以下方法:

&#13;
&#13;
var data = { query: { search: [
  {ns: 0, title: "Help", size: 3677, wordcount: 433},
  {ns: 0, title: "Online help", size: 7326, wordcount: 380},
  {ns: 0, title: "Help desk", size: 9491, wordcount: 1296}
]}};

for (var i = 0; i < data.query.search.length; i++) {
  var result = data.query.search[i];
  var title = result.title;

  console.log(title);
}
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以使用解决方案https://jsfiddle.net/oebq0ywj/

var data = { query: { search: [
  {ns: 0, title: "Help", size: 3677, wordcount: 433},
  {ns: 0, title: "Online help", size: 7326, wordcount: 380},
  {ns: 0, title: "Help desk", size: 9491, wordcount: 1296}
]}};

for(var i in data.query.search) {
	console.log(data.query.search[i].title);
}

答案 2 :(得分:0)

&#13;
&#13;
var data = { query: { search: [
  {ns: 0, title: "Help", size: 3677, wordcount: 433},
  {ns: 0, title: "Online help", size: 7326, wordcount: 380},
  {ns: 0, title: "Help desk", size: 9491, wordcount: 1296}
]}};


var  titleArray = data.query.search.map(function(arrObj) {
  return arrObj.title;
})

  console.log(titleArray);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
&#13;
&#13;
&#13;