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
Create Nested Object from Flat Object

I have an array of Object like

  [
      {
        "parentId": "uniqueParentId1",
        "parentName": "Parent1",
        "childProp1": "test1",
        "childProp2": "test3"
      },
      {
        "parentId": "uniqueParentId2",
        "parentName": "Parent2",
        "childProp1": "somevals",
        "childProp2": "other vals"
      }
      {
        "parentId": "uniqueParentId2",
        "parentName": "Parent2",
        "childProp1": "somevals 1",
        "childProp2": "other vals 1"
      }
    ]

and I want to combine it based in parentId and create an array of Object like below in Javascript . How can I do it ?

    [
      {
        "id": "uniqueParentId1",
        "name": "Parent1",
        "children": [
          {
            "childProp1": "test1",
            "childProp2": "test3"
          }
        ]
      },
      {
        "id": "uniqueParentId2",
        "name": "Parent2",
        "children": [
          {
            "childProp1": "somevals",
            "childProp2": "other vals"
          },
          {
            "childProp1": "somevals 1",
            "childProp2": "other vals 1"
          }
        ]
      }
    ]

The idea to convert flat object to nested Object is so that I can use the nested Object in Iterations easiely

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You can do it with javascript easily. Create and make new array according to your old array.

var oldArray = [
    {
        "parentId": "uniqueParentId1",
        "parentName": "Parent1",
        "childProp1": "test1",
        "childProp2": "test3"
    },
    {
        "parentId": "uniqueParentId2",
        "parentName": "Parent2",
        "childProp1": "somevals",
        "childProp2": "other vals"
    },
    {
        "parentId": "uniqueParentId2",
        "parentName": "Parent2",
        "childProp1": "somevals 1",
        "childProp2": "other vals 1"
    }
];

var newArray = [];

for (var i = 0; i < oldArray.length; i++) {
    var currentObject = newArray.filter(function (x) { return x.id == 
oldArray[i].parentId })[0];
    if (currentObject == null) {
        var newObj = {
            id: oldArray[i].parentId,
            name: oldArray[i].parentName,
            children: [
                {
                    childProp1: oldArray[i].childProp1,
                    childProp2: oldArray[i].childProp2
                }
            ]
        };
        newArray.push(newObj)
    }
    else {
        currentObject.children.push({
            childProp1: oldArray[i].childProp1,
            childProp2: oldArray[i].childProp2
        });
    }
}
console.log(newArray); // your array is here
about 4 years ago · Juan Pablo Isaza Relatório

0

You can do it like this: loop through your array and create a new array with the data you need, i didn't know what the name variable was supposed to be so i generated it.. if that is supposed to be the parentId number you can extract the digits from o.parentId I've also assumed that except parentId all other object keys are childs...

let arr = [{
    "parentId": "uniqueParentId1",
    "childProp1": "test1",
    "childProp2": "test3"
  },
  {
    "parentId": "uniqueParentId2",
    "childProp1": "somevals",
    "childProp2": "other vals"
  },
  {
    "parentId": "uniqueParentId2",
    "childProp1": "somevals 1",
    "childProp2": "other vals 1"
  }
];


let combined = {};
let parentid = 1;
let childs = {};
arr.map(o => {
  if (!combined[o.parentId]) {
    combined[o.parentId] = {
      id: o.parentId,
      name: "Parent" + parentid,
      children: []
    };
    parentid++;
  }
  childs = {}
  for (const [key, value] of Object.entries(o)) {
    if (key !== 'parentId') childs[key] = value;
  }
  combined[o.parentId].children.push(childs);
});
console.log(combined)

about 4 years ago · Juan Pablo Isaza Relatório

0

You can do:

const flatObjects = [{parentId: 'uniqueParentId1',parentName: 'Parent1',childProp1: 'test1',childProp2: 'test3',},{parentId: 'uniqueParentId2',parentName: 'Parent2',childProp1: 'somevals',childProp2: 'other vals',},{parentId: 'uniqueParentId2',parentName: 'Parent2',childProp1: 'somevals 1',childProp2: 'other vals 1'}]

const result = Object.values(
  flatObjects.reduce((a, c) => {
    const k = `${c.parentId}|${c.parentName}`
    a[k] = a[k] || {
      id: c.parentId,
      name: c.parentName,
      children: [],
    }
    a[k].children.push({
      childProp1: c.childProp1,
      childProp2: c.childProp2,
    })
    return a
  }, {})
)

console.log(result)

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