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



我使用维基百科API搜索维基文章。当我单击提交按钮时,我得到一个 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 中,以便用户可以单击结果并转到相应的页面。(网址:http://../[标题](

该数组位于 data.query.search 中

由于结果是动态的,我可能需要某种 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"); 
}

我怀疑我没有正确定位数组元素、键和值。我感谢任何建议。干杯。

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

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);
}

在这里,您可以使用解决方案 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);
}

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);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

最新更新