Home > Article > Web Front-end > JS realizes the method of dynamically adding attributes to objects
In my work, I have to use the requirement of dynamically adding attributes to jd objects. I found a solution on the Internet. The example is as follows:
1, demo
var aa="maker"; var bb=123; var lists={}; eval("lists."+aa+"="+bb); eval('('+"lists."+aa+"="+bb+')'); console.log(lists);
This method has been tried and it works
2. In the project,
$("#saveform").on("click",function(){ var param={}; //bz订单号 var bzorderid=$("#bzorderid").val(); //获取所有产品 $("#allsk .sk td input").each(function(){ var id=this.id; var name=this.name; var val=$("#"+id).val(); //动态添加属性、赋值 eval("param."+name+"="+val) }); }
is used to traverse the input to obtain the value, and the js object dynamically adds attributes and attribute value.
I hope this article will be helpful to everyone in JavaScript programming.
For more JS methods to dynamically add attributes to objects, please pay attention to the PHP Chinese website for related articles!