Reputation: 883
I know that any json can be easily parsed into a javascript object, but let's say, I am using github API to get the profile of a couple developers, but I want to add to this objects some methods to process some data of those developers and keep the info within the object.
I know mongoose is a good extension that implements the concept of models that can do something similar to what I desire, but on a different approach, using as it uses a database to retrieve the models data. Is there a way to populate an array of models using a json returned from an API?
Maybe my way of approaching this matter is not correct, but I fail to see another way out of this issue.
Thank you for your help
Upvotes: 0
Views: 4224
Reputation: 6888
I don't know if this is what you are asking but you can parse JSON:
getSomethingFromAPI().then(function(dataResponse){
var objectArray = JSON.parse(dataResponse)
})
If it isn't please post some code snippets and clarify your questions.
Per comment: I don't think you can freely add an instance method without writing some code. It could be as simple as taking the parse, and mapping that into instances (using underscore):
var someMethod = function(){
return this.x
}
getSomethingFromAPI().then(function(dataResponse){
var objectArray = _.map(JSON.parse(dataResponse), function(anObject){
anObject.someMethod = someMethod.bind(anObject)
return anObject
})
})
There you could also instantiate object via constructors in the map,
getSomethingFromAPI().then(function(dataResponse){
var objectArray = _.map(JSON.parse(dataResponse), function(anObject){
return new SomeObjectConstructor(anObject.x, anObject.y)
})
})
or perhaps there are more advanced techniques. A functional approach would keep the data and the methods separated...
Upvotes: 3