简体   繁体   中英

how to create Object key & value in JavaScript dynamically from array string

I want to create a JavaScript object dynamically from two arrays of strings. One array is used for the key and another for the value. eg it should create * element.name="xyz"; *etc

 var key=["name","id","surname"];
 var value=[["xyz","01","abc"],["def","02","ghi"]]; 
 var element=new Object();

from the above value it should create an object like this:

    var element=new Object();
    element.name="xyz";
    element.id="01";
    element.surname="abc";

    var element =new Object();
    element.name="def";
    element.id="02";
    element.surname="ghi";

I would go like this :

var value=[["xyz","01","abc"],["def","02","ghi"]]; // notice it's an array of array instead of an array of objects

var elements = [];

for (var i = 0; i< value.length; i++) {
    var elem = new Object();
    for (var j=0; j< key.length; j++) {
        elem[key[j]] = value[i][j];
    }
    elements.push(elem);
}

You can use map and reduce functions to get your result. Map will flatten out array of arrays, and reduce will create object for each array

 const key = ['name', 'id', 'surname'] const values = [ ['xyz', '01', 'abc'], ['def', '02', 'ghi'] ] const result = values.map(row => row.reduce((acc, cur, i) => (acc[key[i]] = cur, acc), {})) console.log(result)

Similar to the other answers but avoiding the inner loop:

var keys = ["name","id","surname"];
var values = [["xyz","01","abc"],["def","02","ghi"]]; // an array of arrays, not objects

function populateObjects(keys, values) {
  var arr = [];
  for (var i = 0, l = values.length; i < l; i++) {
    var obj = {};
    obj[keys[0]] = values[i][0];
    obj[keys[1]] = values[i][1];
    obj[keys[2]] = values[i][2];
    arr.push(obj);
  }
  return arr;   
}

var arr = populateObjects(keys, values);
console.log(arr);

Create dynamic object using this

    let featureConfigsData: any = {};
    // let featureConfigsData = new Object();

    if (feature_configs) {
      feature_configs.map((item: any, index: number) => {
        featureConfigsData["" + item.name + ""] = item.value;
      });
      console.log("K_____  ", featureConfigsData);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM