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