这是我的数组定义(可能存在问题。我想说这个数组将是自定义对象的数组):
const records: {LicencePlate: string, Description: string,
SetToUse: string, Depot: string, Active: boolean}[] = [];
然后我要填充它:
this.grid.gridView.data.forEach(element => {
records.push(element.LicencePlate, element.Description, element.DateOfStartUse.toLocaleDateString('en-GB'),
element.Base, element.Active);
});
我想得到这样的东西-对象数组
[{"Johnny", "Actor", "05/03/2000", "Holywood", true},
{"Kirk", "Musician", "01/06/1999", "California", true},
{"Elvis", "Singer", "15/09/1975", "Mississippi", false}]
但是我只有一个很长的单值数组:
["Johnny", "Actor", "05/03/2000", "Holywood", true,
"Kirk", "Musician", "01/06/1999", "California", true,
"Elvis", "Singer", "15/09/1975", "Mississippi", false]
我在哪里弄错了?
答案 0 :(得分:1)
您需要在每次迭代时将一个新对象推入数组。
类似的东西:
this.grid.gridView.data.forEach(element => {
// create object for this row
const o = {
LicencePlate: element.LicencePlate,
Description: element.Description,
/// other properties and values
}
// push that object to array
records.push(o);
});
答案 1 :(得分:0)
-编辑糟糕,这是js,您想要ts ..忽略。我将把它留在这里。
除了charlietfl的答案外,有关
<array>.push
:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push
arr.push(element1[, ...[, elementN]])
您要想要将单个元素最后放入数组索引中,
但是您正在将元素的每个字段按新索引推入数组。
charlietfl的答案实际上是每个元素的浅表重复, 您也可以直接直接推送元素:
let records = []; //or new Array();
//typescript will let you do new Array<Record>(), but not in javascript
this.grid.gridView.data.forEach(element => {
records.push(element);
});
我执行的记录:
//An implementation of your record object (you apparently already have these, so you don't need it)
class Record {
constructor (licensePlate) {
this.licensePlate = licensePlate;
this.description = description;
this.setToUse = setToUse;
this.depot = depot;
this.active = active;
}
}
let records = new Array(); //In typescript we can have Array<Record> for typed array, but not in js :(
//I'm creating a test record here because I don't have your gridView code
let rec = new Record("BLAHBLAH", "A record example instance", "some kind of set to use", "a depot", false);
records.push(rec); //Push the record instance|object into the array
//this.grid.gridView.data.forEach(element => {
// records.push(element.LicencePlate, element.Description, element.DateOfStartUse.toLocaleDateString('en-GB'),
// element.Base, element.Active);
//});