如何将嵌套JSON映射到具有函数的Object结构
How to map nested JSON to an Object structure with functions?
我想映射一个这样的结构:
{
"stuff": {
"onetype": [
{"id":1,"name":"John Doe"},
{"id":2,"name":"Don Joeh"}
],
"othertype": {"id":2,"company":"ACME"}
},
"otherstuff": {
"thing": "some value"
}
}
转换为一个对象,该对象包含两个对象数组(stuff和other stuff)。我想建立这个JSON对象的原型,以便我有我所有的功能可用。我希望能够做这样的事情(树是父对象)。tree.display()
,其中显示函数将考虑数组的一种类型,并调用函数显示在包含对象上。
有简单的方法吗?有人能给我举个例子吗?我可以使用$.extend
这样的函数吗?
this is not working:
$(document).ready(function(){
JSONString = ''
{"stuff": '
{"onetype": '
[{"id":1,"name":"John Doe"},'
{"id":2,"name":"Don Joeh"}],'
"othertype": '
{"id":2,"company":"ACME"}'
}, '
"otherstuff": {"thing": "some value" }'
}';
function Tree () {
this.stuff = new StuffObject();
this.otherstuff;
this.showValue = function () {
$("body").append(this.otherstuff.thing);
}
}
function StuffObject () {
this.onetype = new Array();
this.othertype = new OthertypeObject();
}
function OthertypeObject () {
this.id = 0;
this.company = "unspecified";
this.showCompany = function(){
console.log(this.company);
}
}
var firstTree = $.extend(true, new Tree, JSON.parse(JSONString));
console.log(firstTree);
firstTree.showValue();
firstTree.stuff.othertype.showCompany();
});
如果你只想显示某些字段,你可以试试这个,它会给出公司名称:
<script>
alert("see this");
JSONString = ''
{"stuff": '
{"onetype": '
[{"id":1,"name":"John Doe"},'
{"id":2,"name":"Don Joeh"}],'
"othertype": '
{"id":2,"company":"ACME"}'
}, '
"otherstuff": {"thing": "some value" }'
}';
function Tree () {
this.stuff = new StuffObject();
this.otherstuff;
this.showValue = function () {
$("body").append(this.otherstuff.thing);
}
}
function StuffObject () {
this.onetype = new Array();
this.othertype = new OthertypeObject();
}
function OthertypeObject () {
this.id = 0;
this.company = "unspecified";
this.showCompany = function(){
console.log(this.company);
}
}
var firstTree = $.extend(true, new Tree, JSON.parse(JSONString));
// var x=json_encode(firstTree);
console.log(firstTree);
var x = JSON.stringify(firstTree.stuff.othertype.company);
alert(x);
</script>
相关文章:
- 函数未在Object.keys或Object.getOwnPropertyNames下列出,但可以调用
- 如何取消object.prototypes javascript的一个函数
- 具有子类的构造函数中的Object.freeze
- Object.assign(),函数方法和内存使用
- 使用元素选择器向Object添加函数
- 成员函数中的Javascript“this”object==“window”
- 这在 Object 方法中不引用对象,而是引用函数绑定到的标记
- 有人可以解释一下Object.defineProperty如何在javascript的构造函数中工作
- 运行咕噜咕噜咕噜抛出 _.object 不是函数错误
- 从Object Literal调用函数
- 将函数参数传递给Object.assign
- 不涉及私有“函数”的“Object.create”的自定义实现
- 在NodeJS中传递回调函数变成Object
- Underscore.js:具有_.object函数的意外行为
- Javascript错误Object函数没有方法'url'
- Array.insert函数错误,因为Object函数Array(){〔本机代码〕}没有方法'插入'
- 用于更改object.object属性的函数
- 访问Object字段的JavaScript函数
- TypeError:对象函数Object(){〔本机代码〕}没有方法'方法'
- 如何找到属性的set/get函数(Object.defineProperty)