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

114
Vistas
Array of object into a nested object for every value in the array

Trying to turn an array of objects into a nested object. Is there a good method for this? and how do I make it depending on the array length?

Working but is not universal: https://codesandbox.io/s/thirsty-roentgen-3mdcjv?file=/src/App.js

What I have:

sorting: [
    {
    "id": "HighestDegree",
    "options": [
            "HighSchool",
            "Undergraduate",
            "Bachelor",
            "Master",
            "Doctor"
        ]
    },
    {
    "id": "gender",
    "options": [
            "male",
            "female"
        ]
    }
]

What I want:

value: {
    "Region": "Oklahoma",
    "HighestDegree": {
        "HighSchool": {
            "male": null,
            "female":null
        },
        "Undergraduate":{
            "male": null,
            "female":null
        }
    //and so on...
    }
}

The code beneath works but is hardcoded for only two different options. I want it to be able to nest the length of the array. So lets say another object was age it would be {"HighSchool":{male:{"<25":null,"25-35":null}}} etc..

function testSortingArray() {
    let sorting = [
      {
        id: "HighestDegree",
        options: ["HighSchool", "Undergraduate", "Bachelor", "Master", "Doctor"]
      },
      {
        id: "gender",
        options: ["male", "female"]
      }
    ];
    let GoalArray = {};
    if (sorting.length > 0) {
      sorting[0].options.map((firstArray) => {
        let currObject = {};
        sorting[1].options.map((secondOption) => {
          currObject[secondOption] = null;
        });
        GoalArray[firstArray] = currObject;
      });
    }
    return GoalArray;
  }
  console.log(testSortingArray());
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can do it with a recursive function.

The function below reduces every options array to an object, and then continues populating that object if there are rest elements left from the original sorting array.

const fn = ([{ options }, ...rest]) => options.reduce((a, v) => ({
  ...a,
  [v]: rest.length ? fn(rest): null
}), {});
const result = fn(sorting);

Besides the reduce() method, the code above makes use of object and array destructuring and spread syntax.


Complete snippet:

const sorting = [{
  "id": "HighestDegree",
  "options": [
    "HighSchool",
    "Undergraduate",
    "Bachelor",
    "Master",
    "Doctor"
  ]
}, {
  "id": "gender",
  "options": [
    "male",
    "female"
  ]
}, {
  "id": "age",
  "options": [
    "<25",
    "25-35"
  ]
}];

const fn = ([{ options }, ...rest]) => options.reduce((a, v) => ({
  ...a,
  [v]: rest.length ? fn(rest): null
}), {});
const result = fn(sorting);

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