How to dynamically add attributes to objects using JS

Source: Internet
Author: User
This article mainly introduces how to dynamically add attributes to an object by using JavaScript. It involves simple skills in JS property traversal, Dynamic assignment, and eval, you can refer to the requirements for dynamically adding attributes to the jd object for your work. You can find 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 is acceptable.

2. Use in projects

$ ("# Saveform "). on ("click", function () {var param = {}; // bz Order No. var bzorderid = $ ("# bzorderid "). val (); // get all products $ ("# allsk. sk td input "). each (function () {var id = this. id; var name = this. name; var val = $ ("#" + id ). val (); // dynamically add attributes and assign values to eval ("param. "+ name +" = "+ val )});}

Retrieve the value through input, and dynamically add attributes and attribute values to the js object.

I hope this article will help you design JavaScript programs.

For more articles about how to dynamically add attributes to an object using JS, refer to PHP!

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.