Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

137
Vistas
Javascript nested array to object conversion

I have an array of objects in the following format. It basically a nested array of objects. I tried to do it using a recursive function, but I failed to organize the nested object.

[
  {
    "id": "31a3sd2f1a3ds21f",
    "name": "Energy device",
    "child": [
      {
        "id": "65sa4d65a4sdf654adsf",
        "name": "Device 2",
        "child": [
          {
            "id": "65a4d65ad4s54adsf",
            "name": "Device 3",
            "child": []
          }
        ]
      }
    ]
  },
  {
    "id": "6as54d54as5f",
    "name": "Energy device 2",
    "child": [
      {
        "id": "9a8s7df98a78sdf",
        "name": "Device 4",
        "child": [
          {
            "id": "65a4d65ad4s54adsf",
            "name": "Device 5",
            "child": []
          }
        ]
      },
      {
        "id": "65asd54as5f4",
        "name": "Device 5-1",
        "child": []
      }
    ]
  }
]

I want to convert it to the following format.

{
  "31a3sd2f1a3ds21f": {
    "65sa4d65a4sdf654adsf": {
      "65a4d65ad4s54adsf": ""
    }
  },
  "6as54d54as5f": {
    "9a8s7df98a78sdf": {
      "65a4d65ad4s54adsf": ""
    },
    "65asd54as5f4": ""
  }
}

Is there anyone who can help me?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

I don't know why you wanted the final child to be an empty string instead of an empty object, but here it is:

function arrayToObject(array) {
    // Create empty object if array has cildren, else create an empty string
    const obj = array.length > 0 ? {} : '';

    // Recursively add children to object
    array.forEach((item) => {
        obj[item.id] = arrayToObject(item.child);
    });

    return obj;
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

You can map each object within your array to new arrays of the shape [key, value]. For each object, you can extract the id and child properties using desturcutring assignment in your callback argument ({id, child}) => ...). You can then return an array for that object that represents an entry for the new object your building. The key is the id of the current object, and the value is either a new object based on the child array which you can build by doing a recursive call, or an empty string if your current object doesn't have any children. This allows you to add the nesting to the objects as you build them. Finally, you can wrap the mapped version of your arr into a call to Object.fromEntries() which allows you to convert the array of [key, value] pair entries into an object:

const arr = [ { "id": "31a3sd2f1a3ds21f", "name": "Energy device", "child": [ { "id": "65sa4d65a4sdf654adsf", "name": "Device 2", "child": [ { "id": "65a4d65ad4s54adsf", "name": "Device 3", "child": [] } ] } ] }, { "id": "6as54d54as5f", "name": "Energy device 2", "child": [ { "id": "9a8s7df98a78sdf", "name": "Device 4", "child": [ { "id": "65a4d65ad4s54adsf", "name": "Device 5", "child": [] } ] }, { "id": "65asd54as5f4", "name": "Device 5-1", "child": [] } ] } ];

const mapToId = (arr) => Object.fromEntries(arr.map(({id, child}) => [
  id, child.length ? mapToId(child) : ""
]));

const res = mapToId(arr);
console.log(res);

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda