объект muliple не помещается в массив и не создает массив объекта

#javascript #angular

#javascript #угловой

Вопрос:

 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"},......]
  

Ответ №1:

Используйте 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 )  

Ответ №2:

Вы можете просто использовать 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)  

Ответ №3:

 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));