Given the following Javascript array:
export const myInputArray = [
{
wc:[{f:'fff', n:'nnn'}, {f:'ss', n:'tt'}]
},
{
wc:[{f:'mmm', n:'www'}, {f:'ggg', n:'kkk'}]
} ,
{
wc:[{f:'mmm', n:'www'}, {f:'WWW', n:'CCC'}, {f:'UUU', n:'iii'}]
}
];
and the following Typescript class:
class WC {
constructor (public readonly f:string, public readonly n:string) {
this.f = f;
this.n = n;
}
What is the correct way to iterate through myInputArray
and return an array, each element of which will itself be an array of WC
objects?
The following:
import {myInputArray} ...,
...
myInputArray.forEach( (a: { f: any; n: any; }) => {
const wc = new WC(a.f, a.n);
...
});
throws this error: TypeError: Cannot read property 'forEach' of undefined
,
Thanks
2
Answers
First of all your
import
needs to be fixedThen for creating the instance list you can
reduce
yourmyInputArray
to an 1D-array and then use that for instantiation.No reason to do this "in typing", make your life easier by writing it as normal code:
And then you import that as:
No weird postprocessing required, just hardcode the data you need, if you’re hardcoding data. And if you’re not hardcoding data, then you import the class and use that for your typing hints: