Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

135
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda