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

134
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 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