1
votes

I am trying to loop through my data source objects by doing something like:

this.datasource.data.forEach()

but it doesn't recognize my data is an array of objects so I try this:

 const objects: ObjectModel[] = this.datasource.data

and then I get the following error:

object type is assignable to very few other types

How can I be able to do a forEach on the datasource data?

Updated to include model definition:

ObjectModel = {
id: string,
firstName: string,
lastName: string
}
2
You should include an example of what your data looks like. Without this, we will not be able to answer your question. - Chris Knight
@ChrisKnight i have updated my question to include the model. The data is an array of ObjectModels, I don't know how that helps answer the answer. The problem is not what the model looks like, the problem is getting to recognize the data as an object of my model type. - Nick
It would also be useful to see your forEach() code and what error you might get when you refer to but it doesn't recognise my data is an array of objects - Chris Knight

2 Answers

1
votes

Assign your object to Datasource like below,

datasource: MatTableDataSource<ObjectModal> = [{
id: 1, firstName: 'David', lastName: 'Joe'},
{id: 2, firstName: 'Jeol', lastName: 'Jare'}]

const objects: ObjectModal[] = datasource.data;

Note: Refer from https://stackblitz.com/angular/dnbermjydavk?embed=1&file=app/table-overview-example.html

0
votes

You cannot forEach an object. There are ways to iterate through an object though...

Object.keys

Object.values

Object.entries

Those are some popular ones.

You can check this reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries

If you do have an array of objects, then you should be able to use forEach. But the data you posted is not that format.

for (let [key, value] of Object.entries(objectModel)) {
  console.log(`${key}: ${value}`);
}