muliple对象未推入数组且未创建对象数组

时间:2019-03-13 10:32:37

标签: javascript angular

var myArray = ["id", "name", "location", "email", "gender", "tel / fax", "language preference", "credit card type"]

    for (var key in myArray) {
        this.col.data = myArray[key];
        this.col.type = "text";
        console.log('col=>' + JSON.stringify(this.col))
        this.dynamicColumns.push(this.col);
        console.log('dynamicColumns=>' +            
        JSON.stringify(this.dynamicColumns))       
    }

but i want this output:- [{"data":"id","type":"text"},{"data":"name","type":"text"},{"data":"location","type":"text"},......]

3 个答案:

答案 0 :(得分:3)

使用array.prototype.map 遍历数组,并返回具有新值的新数组。

var myArray = ["id", "name", "location", "email", "gender", "tel / fax", "language preference", "credit card type"]

this.dynamicColumns = myArray.map(ele => {
	return { data: ele, type: 'text' }
})
console.log(this.dynamicColumns )

答案 1 :(得分:1)

您可以简单地使用map并为每个元素以所需格式创建对象。

var myArray = ["id", "name", "location", "email", "gender", "tel / fax", "language preference", "credit card type"]

let op = myArray.map(ele =>({ data: ele, type: 'text' }))

console.log(op)

答案 2 :(得分:0)

var myArray = ["id", "name", "location", "email", "gender", "tel / fax", "language preference", "credit card type"];

var dynamicColumns = [];

for (var key in myArray) {
  this.col = {};
  this.col.data = myArray[key];
  this.col.type = "text";
  console.log('col=>' + JSON.stringify(this.col))
  dynamicColumns.push(this.col);

}
console.log('dynamicColumns=>' +
  JSON.stringify(dynamicColumns));