JS automatically generates object properties sample code _javascript Tips

Source: Internet
Author: User

For example we have an object like the following

Copy Code code as follows:

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 will generally do the following, obj.a.b.c={},obj.a.b.c.d={}, obj.a.b.c.d.f= "FF", but if I have a lot of properties, such a method is not feasible. Now provides a way to automatically generate object properties
Copy Code code as follows:

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"; The name of the object 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;

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.