JS Dynamic Add Object

Source: Internet
Author: User

JS array, string, object operation is an indispensable part of implementing some functions.

In general, JS array and string dynamic add up more convenient, have their own methods, the array of push (), the string directly with the plus sign and so on. But the JS object will need a little work to add dynamically.

Now I've written two ways to add objects dynamically

First Kind

    function toObj1 (key,val) {           var data = {};             = val;            return data;       }        var obj1 = toObj1 (' name ', ' Nurdun ');       Console.log (obj1);

The second Kind

    function ToObj2 (key,val) {           var data = {[Key]:val};            return data;       }        var obj2 = toObj2 (' name ', ' Nurdun ');       Console.log (OBJ2);

Here are the applications of these two methods

First set two arrays, one for key, one for Val

var keyarr= ["Name", "Age", "job"var valarr = ["Nurdun", 3, "front-end"]

Here are two types of dynamically added objects

    function fn (Keyarr,valarr) {           var  data = {};             for (i = 0;i<keyarr.length;i++) {               var  key = keyarr[i];                var  val = Valarr[i];                = val;           }            return data;       }         var op = fn (keyarr,valarr);       Console.log (OP);

The following method is the previous key will be overwritten by the following key

    function Fun (Keyarr,valarr) {           var  data = {};             for (i = 0;i<keyarr.length;i++) {               var  key = keyarr[i];                var  val = Valarr[i];                = {[Key]:val};           }            return data;       }        var op1 = Fun (keyarr,valarr);       Console.log (OP1);

JS Dynamic Add Object

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.