I am returning JSON from an API via a $.ajax request and end up with a lump of JSON:
var result = {
"status": 200,
"offset": 5,
"limit": 25,
"total": 7,
"url": "/v2/api/dataset/topten?",
"results": [
{
"datasets": [
"dataset",
"tt_all"
],
"id": "Hxb6VtpFRQ9gEr",
"title": "Venues",
"type": "topten",
"url": "/v2/dataset/topten/Hxb6VtpFRQ9gEr"
},
}
Or something similar. There are nested arrays containing more results in larger requests.
I would like to parse this information, put it into an object and have methods for available for that object to extract specific bits of information, from all levels - something like:
result.title => "Venues" or result.id => "Hxb6v...."
However, the output from the AJAX request can be assigned to a var by a user defined so I would like to make a function to stick this in an object with methods available before it exits the ajax success function and get assigned to result or whatever.
I don't particularly want to go down the:
Object.prototype.method = function(){ // extend Object here }
method as it makes people angry.
If I make another object to extend the prototype:
function Datalump(){};
Datalump.prototype.title = function(){
// get title or something here
};
I am struggling with what to pass to what and assigning things to the wrong thing.
How do I go about this method / object creation?
Any suggestions or pointers would be greatly appreciated.
UPDATE: Thank you all for the help - it's been very enlightening. I've marked Mike Brant's answer as correct as it seems the most appropriate to the question I asked. George Jempty's answer was also a very useful learning experience.
I'm actually going in a slightly different direction in the project (new requirements!), but parts of all the answers will probably make it into the 'alpha'.
Many thanks all.