I have an array called rows of type TestEvent, and want to push to the array, i cant get to output the object i pushes it only shows undefined As you can see this.rows shows the arrays, but when i try to output a spesific array this.rows[0] i get undefined. (Typescript 2.7, Angular 5)
I've tried the following guides:
import { TestEvent } from '../../models/event'
rows: TestEvent[] = []
public push(){
var test: TestEvent = {id: '222', category:'testcat', event_name: 'name'}
console.log(test) // Outputs the array
this.rows.push(test) //Push the array to this.rows
console.log(this.rows) //Outputs array of objects
consloe.log(this.rows[0]) //Outputs undefined
}
Event.ts
export interface TestEvent{
id?: string,
category?: string,
event_name?: string
}
How do you push an array of objects in another array in TypeScript? Use the concat function, like so: var arrayA = [1, 2]; var arrayB = [3, 4]; var newArray = arrayA. concat(arrayB); The value of newArray will be [1, 2, 3, 4] ( arrayA and arrayB remain unchanged; concat creates and returns a new array for the result).
To define an interface for an array of objects, define the interface for the type of each object and set the type of the array to be Type[] , e.g. const arr: Employee[] = [] . All of the objects you add to the array have to conform to the type, otherwise the type checker errors out.
To push an object into an array, call the push() method, passing it the object as a parameter. For example, arr. push({name: 'Tom'}) pushes the object into the array. The push method adds one or more elements to the end of the array.
TypeScript - Array push()push() method appends the given element(s) in the last of the array and returns the length of the new array.
That code has no problem and I tested on my local(typescript : 2.5 , angular5). And I got "row[0] : {id: "222", category: "testcat", event_name: "name"}"
interface TestEvent{
id?: string,
category?: string,
event_name?: string
}
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
rows: TestEvent[] = [];
ngOnInit(){
var test: TestEvent = {id: '222', category:'testcat', event_name: 'name'};
console.log(test); // Outputs the array
this.rows.push(test); //Push the array to this.rows
console.log(this.rows); //=> 0:{id: "222", category: "testcat", event_name: "name"}
console.log(this.rows[0]); // => {id: "222", category: "testcat",event_name: "name"}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With