Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

90
Vistas
How to transform an array with some deep nesting into another object in order to manipulate expanding initialState in React-table

I have this data:

const data = [
  {
    "id": 1,
    "subRows": [
      {
        "id": 1,
        "subRows": [
          {
            "id": 1,
          }
        ]
      },
      {
        "id": 2,
        "subRows": [
          {
            "id": 4,
          }
        ]
      },
    ]
  },
  {
    "id": 55,
    "subRows": []
  }
];

and i need to get from this data like that, that will relay all the nesting of starter data:

const result = {
  '0': false,
  '0.0': false,
  '0.0.0': false,
  '0.1.0': false,
  '0.1.1': false,
  '1: false'
}

I need it in order to represent nesting in starting data and transform it to format, that react-table expended initial state is require. (https://react-table.tanstack.com/docs/api/useExpanded). I want to store it in local storage to prevent expanding state changing with page reload.

7 months ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Take a recursive approach and ahnd over the last key as new prefix.

const
    flat = (array, prefix = '') => array.reduce((r, o, i) => {
        const key = prefix + (prefix && '.') + i;
        return {
            ...r, 
            [key]: false,
            ...flat(o.subRows || [], key)
         };
    }, {});

    data = [{ id: 1, subRows: [{ id: 1, subRows: [{ id: 1 }] }, { id: 2, subRows: [{ id: 4 }] }] }, { id: 55, subRows: [] }],
    result = flat(data);

console.log(result);

7 months ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos