arraysangulartypescriptobjectarrayofarrays

I need to convert an array of arrays into an arrays of objects


I am trying to convert an array of arrays into an array of objects, I am working with Angular and TypeScript, this is the code:

look(data: [][]){
    
    const found = data.flatMap( element => element ).find(element => element == this.codigo );
    console.log(found);

    const dataobj = data.map(function(row){
      return {
        a: row[0],
        b: row[1],
        c: row[2],
        d: row[3],
        e: row[4],
        f: row[5],
        g: row[6],
      }
    });
    console.log(dataobj);
    console.log(this.datos);
    

  }

And I am getting this error: src/app/hojaexcel/hojaexcel.component.ts:61:16 - error TS2493: Tuple type '[]' of length '0' has no element at index '0'.

61 a: row[0], ~


Solution

  • The type [] is a tuple type and not an array type. You can have [number], [number, string] etc... these are all tuple types. [] would be a tuple with no elements. [][] is a tuple of a tuple with no elements, literally [[]].

    You need to declare a type for it to be an array of an array. I'm not sure what data is supposed to be, but let's assume it is a number:

    look(data: number[][]) {