如何将由数组组成的数组转换为由对象组成的数组(定义新属性)?

时间:2017-11-23 07:39:37

标签: javascript arrays object

如何将此问题:[[a1, b1], [a2, b2]]转换为此内容? [{x1: a1, y2: b1}, {x2: a2, y2: b2}]

注意:x1x2是新定义的属性(a1b1等作为值。)

注意:这是我试过的:

formatData.map((data, index) => {
  const obj = {
    dataX: data[index][0],
    dataY: data[index][2]
  }
  data = obj
}

但是卡住了。

4 个答案:

答案 0 :(得分:3)

简单的for循环可以做到这一点



var arr = [["a1", "b1"], ["a2", "b2"]];
var newArr = [];
var repeater = ['x','y','z'];//...
for(var i in arr){
  var obj = {};
  for(var j in arr[i]){  
    obj[repeater[j]+(parseInt(i)+1)] = arr[i][j];
  }
  newArr.push(obj);
}
console.log(newArr);




答案 1 :(得分:1)

您可以使用.map数组,如下所示

var temp = [['a1', 'b1'], ['a2', 'b2']];

temp.map(function(arr,index){
   var ret = {};
   ret['x'+(index+1)]= arr[0];
   ret['y'+(index+1)]= arr[1];
   return ret;
});

//"[{"x1":"a1","y1":"b1"},{"x2":"a2","y2":"b2"}]"

答案 2 :(得分:1)

使用forEach



var m = [
  ['a1', 'b1'],
  ['a2', 'b2']
];
var tempArray = []
m.forEach(function(item, index) {
  // create a local object to set the key and value into it
  var localObj = {};
  // setting key and value
  localObj['x' + 1] = item[0];
  localObj['y' + 1] = item[1]
  // push that pbject to an array
  tempArray.push(localObj)
})

console.log(tempArray)




答案 3 :(得分:0)

您可以映射值并将Object.assign用于新对象。

var keys = ['x', 'y'],
    data = [['a1', 'b1'], ['a2', 'b2']],
    result = data.map(a => Object.assign(...keys.map((k, i) => ({ [k]: a[i] }))));
    
console.log(result);

使用所需键和相应索引的对象。

var keys = { x: 0, y: 2 },
    data = [['a1', 'b1', 'c1'], ['a2', 'b2', 'c2']],
    result = data.map(a => Object.assign(...Object
        .keys(keys)
        .map(k => ({ [k]: a[keys[k]] }))
    ));
    
console.log(result);