将json数据转换为带有方法的对象的最简单方法? [英] Easiest way to convert json data into objects with methods attached?
问题描述
将包含对象数据的json转换为带有方法的实际对象的最快,最简单的方法是什么?
通过示例的方式,我获得了一个果钵的数据,该果钵具有一系列水果对象,这些水果对象进而包含一系列种子:
By way of example, I get data for a fruitbowl with an array of fruit objects which in turn contain an array of seeds thus:
{"fruitbowl": [{
"name": "apple",
"color": "red",
"seeds": []
},{
"name": "orange",
"color": "orange",
"seeds": [
{"size":"small","density":"hard"},
{"size":"small","density":"soft"}
]}
}
这一切都很好,但是在客户身上,我们用这种水果做东西,比如吃它并种下树木...
That's all nice and good but down on the client we do stuff with this fruit, like eat it and plant trees...
var fruitbowl = []
function Fruit(name, color, seeds){
this.name = name
this.color = color
this.seeds = seeds
this.eat = function(){
// munch munch
}
}
function Seed(size, density){
this.size = size
this.density = density
this.plant = function(){
// grow grow
}
}
我的ajax的成功例程当前正在遍历该事物并依次构造每个对象,并且它还不能处理种子,因为在我遍历遍历种子构造函数之前,我正在思考
My ajax's success routine currently is currently looping over the thing and constructing each object in turn and it doesn't handle the seeds yet, because before I go looping over seed constructors I'm thinking
有没有更好的方法?
success: function(data){
fruitbowl.length = 0
$.each(data.fruitbowl, function(i, f){
fruitbowl.push(new Fruit(f.name, f.color, f.seeds))
})
我还没有探索过按原样循环对象并附加所有方法的问题.那行得通吗?
I haven't explored looping over the objects as they are and attaching all the methods. Would that work?
推荐答案
将数据传递给对象构造函数,然后使用jquery的"extend"组合数据和方法:
Pass the data to the object constructor then use jquery's "extend" to combine the data and methods:
function Fruit(data){
$.extend(this, data)
this.eat = function(){
// munch munch
}
}
...
$.each(data.fruitbowl, function(i, f){
fruitbowl.push(new Fruit(f))
})
您仍然涉及到循环;并且必须手动为嵌套对象(例如种子)编写循环代码,但这仍然是解决问题的一种非常简单的方法.
You still have loops involved; and must manually code loops for the nested objects (like seeds), but still a very simple way to get past the problem.
这篇关于将json数据转换为带有方法的对象的最简单方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!