如何访问其值为未知整数的JS对象属性? [英] How can I access a JS object property whose value is an unknown integer?
问题描述
此Wikipedia API调用返回的JSON响应是一系列嵌套对象.要遍历对象属性链并访问感兴趣的文本,我首先必须访问一个值为随机数的属性,具体取决于我按标题查询的维基百科页面.
The JSON response returned from this wikipedia API call is a series of nested objects. To travel down the object property chain and access the text of interest, I have to first access a property whose value is a random number, dependent upon the wikipedia page I query by title.
标题为"San%20Francisco"
的页面的示例(页面ID = 49728):
An example for the page titled "San%20Francisco"
(page id = 49728):
对象属性链:
responseJSON.wiki[0].query.pages[<<page id>>].extract
API调用示例:是否可以通过某种方式识别值是随机整数的属性?链中只有一个页面的子页面,其值为整数.我想不出另一种解决方案,也不知道任何有效的JSON解析方法.
Is there some way that I can identify the property whose value is a random integer? There is only one child of pages in the chain whose value is an integer. I cannot think of another solution and do not know of any JSON parsing method that would be effective.
我对AJAX请求没有经验,并且正在使用jQuery以这种方式进行ajax调用.如果我天真地做些事情,我想提一下:
I am inexperienced with AJAX requests and am making my ajax call in this way using jQuery. I would like to mention this in case I am doing something naive:
var getWiki = function (obj) {
return $.ajax({
url: "http://en.wikipedia.org/w/api.php" +
"?origin=*" + "&format=json" +
"&action=query" + "&prop=extracts" +
"&exintro=" + "&explaintext=" + "&titles=" +
obj.position,
method: 'GET'
});
};
推荐答案
如果您的object
只有一个键,则可以使用Object.keys(object)[0]
获取它,然后对原始object
. (这是dig
实用程序在下面的示例中所做的.)
If your object
has only a single key, you can get it using Object.keys(object)[0]
and then perform a dynamic bracket-notation property access on the original object
. (This is what the dig
utility does in the example below.)
还请注意,您可以使用.promise()
来使您的JSON响应处理更加整齐.我建议您也将type: 'json'
添加到AJAX请求中,这样就不必自己解析字符串数据.
Also note that you can use .promise()
to make handling your JSON response a bit tidier. I would suggest you add type: 'json'
to your AJAX request, too, so that you don't have to parse the string data yourself.
function getWiki(obj) {
return $.ajax({
url: "http://en.wikipedia.org/w/api.php" +
"?origin=*" + "&format=json" +
"&action=query" + "&prop=extracts" +
"&exintro=" + "&explaintext=" + "&titles=" +
obj.position,
method: 'GET',
type: 'json'
}).promise()
}
function dig(object) {
return object[Object.keys(object)[0]]
}
getWiki({
position: 'San Francisco'
})
.then(function(json) {
console.log(
dig(json.query.pages).extract //=> 'San Francisco (SF) ...'
)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
这篇关于如何访问其值为未知整数的JS对象属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!