要对家庭结构进行建模,我使用了简单的Person
类,并且可以将结构另存为文本,然后以另一种方式使用。但是我的班级有不同的方法对我的代码有用且不可或缺,我找到了第一个对象的方法,但是如何继续深入?
深度为1,但最多可以达到6
let json = {"name":"SON","date":"2000-01-01T05:00:00.000Z","sex":"H",
"dad":{"name":"DAD","date":"2000-01-02T05:00:00.000Z","sex":"H","dad":null,"mom":null},
"mom":{"name":"MOM","date":"2000-01-03T05:00:00.000Z","sex":"F","dad":null,"mom":null}
};
class Person {
constructor(name, date, sexe) {
this.name = name;
this.date = date;
this.sexe = sexe;
this.dad = null;
this.mom = null;
}
doStuff(){
console.log(this.name);
}
}
let obj = Object.assign(new Person,json);
//OK
obj.doStuff();
//NOK 'obj.dad.doStuff is not a function' as 'dad' is not associated to Person
obj.dad.doStuff();
答案 0 :(得分:3)
您可以递归地执行此操作,如果不是Object.assign
,则调用对dad
和mom
执行null
的相同函数:
let json = {
"name": "SON", "date": "2000-01-01","sex": "H",
"dad": {
"name": "DAD","date": "2000-01-02","sex": "H", "dad": null,"mom": null
},
"mom": {
"name": "MOM","date": "2000-01-03","sex": "F","dad": null,
"mom" : { "name": "GRAMDA","date": "2000-01-02","sex": "F","dad": null,"mom": null }
}
};
class Person {
constructor(name, date, sexe) {
this.name = name;
this.date = date;
this.sexe = sexe;
this.dad = null;
this.mom = null;
}
doStuff() {
console.log(this.name);
}
}
function buildPersons(root) {
let obj = Object.assign(new Person, root);
if (obj.dad) obj.dad = buildPersons(obj.dad);
if (obj.mom) obj.mom = buildPersons(obj.mom);
return obj;
}
let obj = buildPersons(json);
obj.doStuff();
obj.dad.doStuff();
obj.mom.mom.doStuff();