Js automatically generates sample code for properties of objects
- 2020-03-26 21:43:41
- OfStack
For example, we have the following object
var obj = { a : {
b:"bb"
}
}
But now we want to add the following attribute to the obj object: obj.a.b.c.d.f="ff"; We usually do this, obj. A.B.C = {}, obj. A.B.C.D = {}, obj. A.B.C.D.F = "ff"; But if I have a lot of properties, this method won't work. We now provide a way to automatically generate object properties
function autoCreateObjProperty(temString){
var TemObjs = temString.split(".");
for(var i =0;i<TemObjs.length;i++){
var ttt = TemObjs[i];
if(!obj.hasOwnProperty(TemObjs[i])){
var objString="obj";
for(var j= 1;j<=i;j++){
objString+="."+TemObjs[j];
}
obj = eval(objString);
if(obj == undefined){
var temObjString="obj"; //Object name var obj = {}
for(var j= 1;j<i;j++){
temObjString+="."+TemObjs[j];
}
obj = eval(temObjString);
obj[TemObjs[i]]={};
obj={};
}
}else{
obj = obj[TemObjs[i]];
}
}
return obj;
}