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

192
Visualizações
Dynamically group flattened JSON into nested JSON object

Suppose I have the following JSON array:

[
    {
        "MainCategory": "1",
        "SubCategory": "a",
        "Value": "val1"
    },
    {
        "MainCategory": "1",
        "SubCategory": "a",
        "Value": "val2"
    },
    {
        "MainCategory": "1",
        "SubCategory": "b",
        "Value": "val3"
    },
    {
        "MainCategory": "2",
        "SubCategory": "a",
        "Value": "val4"
    },
    {
        "MainCategory": "2",
        "SubCategory": "b",
        "Value": "val5"
    },
    {
        "MainCategory": "2",
        "SubCategory": "b",
        "Value": "val6"
    }
]

And would like to convert it into the following multidimensional object in JavaScript (no Lodash):

{
    "1":{
        "a": [
            "val1",
            "val2"
        ],
        "b": [
            "val3"
        ]
    },
    "2":{
        "a": [
            "val4"
        ],
        "b": [
            "val5",
            "val6"
        ]
    }
}

I figure I can do it with a foreach, but I'm trying to do it using the reduce function (HOPING that is the right one to use here) and just not getting the right syntax.

My current GUESS (not working) is something along the lines of:

const newJson = CurrentJson.reduce((result, {MainCategory, SubCategory, Value}) => {
    (result[MainCategory][SubCategory] = result[MainCategory][SubCategory] || [])
    .push(Value);

    return result;
}, {});

How can I do this?

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

0

You can use a reducer to iterate over the original JSON and build up the new object.

const json = [
    {
        "MainCategory": "1",
        "SubCategory": "a",
        "Value": "val1"
    },
    {
        "MainCategory": "1",
        "SubCategory": "a",
        "Value": "val2"
    },
    {
        "MainCategory": "1",
        "SubCategory": "b",
        "Value": "val3"
    },
    {
        "MainCategory": "2",
        "SubCategory": "a",
        "Value": "val4"
    },
    {
        "MainCategory": "2",
        "SubCategory": "b",
        "Value": "val5"
    },
    {
        "MainCategory": "2",
        "SubCategory": "b",
        "Value": "val6"
    }
]

const newJson = json.reduce((prev, curr) => {
  // Check for the MainCategory first
  if (prev[curr.MainCategory] === undefined) {
    prev[curr.MainCategory] = {
      [curr.SubCategory]: [] // Add the SubCategory key and define as empty array
    }
  }
  
  // Check if we have the SubCategory
  if (prev[curr.MainCategory][curr.SubCategory] === undefined) {
    prev[curr.MainCategory][curr.SubCategory] = [] // define as empty array
  }

  // Push the Value
  prev[curr.MainCategory][curr.SubCategory].push(curr.Value)
  
  return prev
}, {})

console.log(newJson)

about 4 years ago · Juan Pablo Isaza Relatório

0

You may use reduce as follows;

var data = [ { "MainCategory": "1"
             , "SubCategory": "a"
             , "Value": "val1"
             }
           , { "MainCategory": "1"
             , "SubCategory": "a"
             , "Value": "val2"
             }
           , { "MainCategory": "1"
             , "SubCategory": "b"
             , "Value": "val3"
             }
           , { "MainCategory": "2"
             , "SubCategory": "a"
             , "Value": "val4"
             }
           , { "MainCategory": "2"
             , "SubCategory": "b"
             , "Value": "val5"
             }
           , { "MainCategory": "2"
             , "SubCategory": "b"
             , "Value": "val6"
             }
           ],
   res  = data.reduce((r,o) => ( r[o.MainCategory] ? r[o.MainCategory][o.SubCategory] ? r[o.MainCategory][o.SubCategory].push(o.Value)
                                                                                      : r[o.MainCategory][o.SubCategory] = [o.Value]
                                                   : r[o.MainCategory] = {[o.SubCategory]: [o.Value]}
                               , r
                               ) ,{});
  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