How Can I Access A Js Object Property Whose Value Is An Unknown Integer?
Solution 1:
Well, if there is always a single property on pages object then you can try either method:
if (typeofObject.values !== 'function') {
Object.values = obj =>Object.keys(obj).map(key => obj[key]);
}
const responseJSON = {
"batchcomplete": "",
"query": {
"pages": {
"49728": {
"pageid": 49728,
"ns": 0,
"title": "San Francisco",
"extract": "Some text"
}
}
}
}
const pages = responseJSON.query.pages;
const extractedWithKeys = pages[Object.keys(pages)[0]];
const extractedObjValues = Object.values(pages)[0];
console.log(extractedWithKeys, extractedObjValues)
Solution 2:
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.)
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.
functiongetWiki(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()
}
functiondig(object) {
return object[Object.keys(object)[0]]
}
getWiki({
position: 'San Francisco'
})
.then(function(json) {
console.log(
dig(json.query.pages).extract//=> 'San Francisco (SF) ...'
)
})
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Solution 3:
You can actually do this without Object.keys
or other similar tricks if you add the indexpageids
parameter to the query.
Example API call: https://en.wikipedia.org/w/api.php?action=query&format=json&prop=extracts&indexpageids=1&titles=San+Francisco&exintro=1&explaintext=1
Example JSON output:
{"batchcomplete":"","query":{"pageids":["49728"],"pages":{"49728":{"pageid":49728,"ns":0,"title":"San Francisco","extract":"San Francisco (initials SF) <snip>"}}}}
Then you can use something like data.query.pages[data.query.pageids[0]].extract
to get the extract (although bear in mind that sometimes no pages may be returned, depending on what query you use).
Wikipedia's API sandbox is useful for discovering parameters like indexpageids
- experimenting there is usually quicker than reading the docs.
Post a Comment for "How Can I Access A Js Object Property Whose Value Is An Unknown Integer?"