Home >Web Front-end >JS Tutorial >js automatically generates object attribute sample code_javascript skills

js automatically generates object attribute sample code_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:18:281135browse

For example, we have the following object

Copy code The code is as follows:

var obj = { a: {
b:"bb"
}
}

But now we want to add the following attributes to the obj object: obj.a.b.c.d.f="ff"; We generally It will be done as follows, obj.a.b.c={}, obj.a.b.c.d={}, obj.a.b.c.d.f="ff"; but if I have many attributes, this method is not feasible. Now provide a method to automatically generate object properties
Copy code The code is as follows:

function autoCreateObjProperty( temString){
var TemObjs = temString.split(".");
for(var i =0;ivar 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"; //The name of the object var obj = {}
for(var j= 1;jtemObjString ="." TemObjs[j];
}
obj = eval(temObjString);
obj[TemObjs[i]]={};
obj={};
}
}else{
obj = obj[TemObjs[i]];
}
}
return obj;

}
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn