skip to Main Content

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


  1. First of all your import needs to be fixed

    import { myInputArray } from 'your/file/path';
    

    Then for creating the instance list you can reduce your myInputArray to an 1D-array and then use that for instantiation.

    const inputList = myInputArray.reduce((acc, cur) => {
      acc = [...acc, ...cur.wc];
      return acc;
    }, []);
    const objectList = inputList.map((a: { f: any, n: any }) => {
      const wc = new WC(a.f, a.n);
      return wc;
    });
    
    Login or Signup to reply.
  2. No reason to do this "in typing", make your life easier by writing it as normal code:

    /**
     * Define your class where you're using it, and export it
     * so that you can import it wherever you need it for TS
     * purposes.
     *
     * But you almost certainly want to rename this class though,
     * "WC" tells you nothing about what it is. Just give it
     * a proper expanded name.
     */
    export class WC {
      public readonly f:string;
      public readonly n:string;
      constructor (f:string, n:string) {
        this.f = f;
        this.n = n;
      }
    }
    
    // And then define the array of data you *actually want*:
    export const WC_ARRAY:WC[] = [
      new WC('fff', 'nnn'),
      new WC('ss', 'tt'),
      ...
    ];
    

    And then you import that as:

    import { WC_ARRAY as myArray } from "./thatfile.js";
    

    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:

    import { WC } from "./thatfile.js";
    
    function handleSomeFetchDataOrSomething(data: WC[]) {
      data.forEach(wc => {
        // TS knows that wc.f and wc.n exist, because you told it so.
      });
    }
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search