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

341
Visualizações
How to create nested JSON using first entry from from flat JSON as parent in javascript

I've tried various answers to this (same/similar) question here, and none have given the desired result. I have a flat Json file that I need to convert to nested. The first item in each chunk is the item that the data needs grouping on when converted to nested data. The example data just shows two "types" but there are several more in the data, and a few more other elements along with colour and size as well - I kept it short for posting here.

Example data input:

[
  {
    "type": "Background",
    "colour": "Blue",
    "size": "5"
  },
  {
    "type": "Background",
    "colour": "Grey",
    "size": "3"
  },
  {
    "type": "Foreground",
    "colour": "Red",
    "size": "5"
  },
  {
    "type": "Foreground",
    "colour": "White",
    "size": "10"
  }
]

Desired Output:

[
  {
    "type": "Background",
    "elements": [
      {
        "colour": "Blue",
        "size": "5"
      },
      {
        "colour": "Grey",
        "size": "3"
      }
    ]
  }
  {
    "type": "Foreground",
    "elements": [
      {
        "colour": "Red",
        "size": "5"
      },
      {
        "colour": "White",
        "size": "10"
      }
    ]
  }
]

The closest I came to an answer for this was here: Create nested json from flattened JSON in javascript

But the output I received from that (in VSCode) was this:

{
  type: { elements: [ [Object], [Object] ] }
}

While I am trying to follow the code, it is beyond my javascript knowledge currently, so I don't know what's going wrong, or why I get [object] and not the actual elements?

Can anyone help me get this sorted out so my output looks like my above "Desired output"?

Cheers!

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

0

You can use the forEach() method to loop over the array, in this case, result. If the type wasn't set in the result, then add the new type. But, if the item already has its type in the result, then just push the item's elements.

const items = [
  {
    type: 'Background',
    colour: 'Blue',
    size: '5',
  },
  {
    type: 'Background',
    colour: 'Grey',
    size: '3',
  },
  {
    type: 'Foreground',
    colour: 'Red',
    size: '5',
  },
  {
    type: 'Foreground',
    colour: 'White',
    size: '10',
  },
];

let result = [];

items.forEach((item) => {
  if (!result.find((x) => x.type === item.type)) {
    result.push({ type: item.type, elements: [] });
  }

  result
    .find((x) => x.type === item.type)
    .elements.push({
      color: item.colour,
      size: item.size,
    });
});

console.log(result);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

about 4 years ago · Juan Pablo Isaza Relatório

0

try this

var output = [];

var newObj = { type: input[0].type, elements: [] };
var prevType = input[0].type;

input.forEach((element) => {
  if (element.type != prevType) {
    output.push(newObj);
    newObj = { type: element.type, elements: [] };
    prevType = element.type;
  }
  newObj.elements.push({ colour: element.colour, size: element.size });
});
output.push(newObj);
about 4 years ago · Juan Pablo Isaza Relatório

0

It seems that there are two steps here. First group all entries with the same type (which would be easier under the type name as a property, then build the nesting.

const input = 
    [
      {
        "type": "Background",
        "colour": "Blue",
        "size": "5"
      },
      {
        "type": "Background",
        "colour": "Grey",
        "size": "3"
      },
      {
        "type": "Foreground",
        "colour": "Red",
        "size": "5"
      },
      {
        "type": "Foreground",
        "colour": "White",
        "size": "10"
      }
    ];

var assist = {},
    output = [];

// Group original objects based on type
// The type is used as a property value
for (let i = 0; i < input.length; i++) {
  let type = input[i].type;
  
  if (assist.hasOwnProperty(type)) {
    assist[type].push(input[i]);
  } else {
    assist[type] = [input[i]];
  }
  delete input[i].type;
}


// Turn the grouped entries into new array entries
let keys = Object.keys(assist);
for (let i = 0; i < keys.length; i++) {
  output.push({
    type: keys[i],
    elements: assist[keys[i]]
  });
};

// Show results
console.log(output);

Note that while the above code does not modify the original array, it does modify it's members (deleting their type property) and using them in the output array. You will have to clone it if you need the original too.

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