Flatten object type with array property in typescript react for output to react-data-grid

410 Views Asked by At

Apologies in advance if this has already been answered, but I am struggling to find an answer to it... I have an array which contains a 2 d array property.

What I want returned is a type which contains has the inner array as a flat object.

So for example my array could be

{
  name: "Widget",
  event: "Xmas",
  pilot: "Dave",
  session: "drinking",
  frameType: "flight",
  stint: 2016,
 plane: "737",
 **data: {
   "114": "137.623",
   "115": "51.090",
}**

}

What I would like is my output to be

{      
name: "Widget",
      event: "Xmas",
      pilot: "Dave",
      session: "drinking",
      frameType: "flight",
      stint: 2016,
     plane: "737",    
     "114": "137.623",
     "115": "51.090",    
,
}

Now here is my code to generate the array.

The Type:

type TableItem =
    {
        name: string,
        event: string,
        session: string,
        frameType: string,
        stint: number,
        chassis: string,
        driver: string,
        data: (string | number)[][]
    };



const getTableItem = (index: number) =>
    {
        const d = data[index];
        //Transformentry just makes the id 3 digits
        const dataItems = Object.assign({}, ...Object.entries(d.data).map(transformEntry));        
        


        const tableItem: TableItem = {
            name: d.name,
            event: d.event,
            piolt: d.pilot,
            session: d.session,
            frameType: d.frameType,
            stint: d.stint,
            plane: d.plane,
            data: dataItems
        };      
        return tableItem;  
    };   

 const rows = (data.map((d, index) => { return getTableItem(index); }));

Now what I want is the rows variable(const) to contain the flattened array. I have tried flat/flatmap and reduce but can't get them to work.

If anyone can point me in the right direction with this it would be massively appreciated. Basically the rows const will then be passed to the react-data-grid component.

Thanks in advance

Steve

1

There are 1 best solutions below

1
On

The data property is not an array, it is another object which may be why things like flatMap did not work for you.

If you're happy to retain the data property but also flatten the properties therein into the top level object you could just flatten it with the spread operator ...:

const input = {
  name: "Widget",
  event: "Xmas",
  pilot: "Dave",
  session: "drinking",
  frameType: "flight",
  stint: 2016,
  plane: "737",
  data: {
   "114": "137.623",
   "115": "51.090",
  }
};

const result = {...input,...input.data};
console.log(result);

If you must get rid of the data property you could just add delete result.data; to the above.