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

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

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