Home  >  Article  >  Web Front-end  >  JS realizes the method of dynamically adding attributes to objects

JS realizes the method of dynamically adding attributes to objects

高洛峰
高洛峰Original
2017-02-08 17:35:461607browse

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!

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