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

99
Visualizações
Create array of objects from sorting another array of objects

I want to create an array of objects, and the first elements from the each data object to be a separate object, the second element from the each data object to be another separate object and so on...

let array = [{   
    data: {
       center1: "1",
       storage1: "1",
       system1: "1",
    }
  },
  {  
    data: {
       center2: "2",
       storage2: "2",
       system2: "2",
    }
  }
]

Expected result:

[
    { center1: "1",  center2: "2"},
    { storage1: "1",  storage2: "2"},
    { system1: "1",  system2: "2"}
]

And this is what I tried do to but is not working really well:)

 const rows = [];
 array.forEach((item, index) => {
      for (let key in item.data) {
          rows.push({index : key + ': ' + item.data[key]});
      }
 });

The output is this:

[
    {index : 'center1: 1'},
    {index : 'storage1: 1'},
    {index : 'system1: 1'},
    {index : 'center2: 2'},
    {index : 'storage2: 2'},
    {index : 'system2: 2'}
]

Thank you for your help!

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

0

This'll be incredibly brittle, because key ordering is irrelevant to how JS objects work, and the assumption that "the first key in each object is the same kind of key" is really only that: an assumption. So, the first thing to fix would be to make all those objects use the same keys, not uniques, thus making "key ordering" irrelevant.

However, if that's not an option (and it almost certain is, but if it's not) then Object.entries will turn any object into a key/value array, which you can then use to restructure this data:

let array = [{   
    data: {
       center1: "1",
       storage1: "1",
       system1: "1",
    }
  },
  {  
    data: {
       center2: "2",
       storage2: "2",
       system2: "2",
    }
  }
]

const restructured = array.reduce((result, e) => {
  Object.entries(e.data).forEach(([key, val], pos) => {
    if (!result[pos]) result[pos] = {};
    result[pos][key] = val;
  });
  return result;
}, []);

console.log(restructured);

about 4 years ago · Juan Pablo Isaza Relatório

0

let array = [{   
        data: {
           center1: "1",
           storage1: "1",
           system1: "1",
        }
      },
      {  
        data: {
           center2: "2",
           storage2: "2",
           system2: "2",
        }
      }
    ]

     const rows = [];
     array.forEach(item => {
          Object.keys(item.data).forEach( (dt, i) => {
              if ( ! rows[i] ) { 
                  rows.push({});
              }
              rows[i][dt] = item.data[dt];
          });
     });
     console.log(rows)

about 4 years ago · Juan Pablo Isaza Relatório

0

You can try something like this, which may probably optimized (of course it will work only if all objects strictly have the same structure) :

  const array = [
    {
      data: {
        center1 : "1",
        storage1: "1",
        system1 : "1",
      }
    },
    {
      data: {
        center2 : "2",
        storage2: "2",
        system2 : "2",
      }
    }
  ];

  const finalArray = [];

  for (let i = 0; i < Object.keys(array[0].data).length; i++) {
    finalArray.push({});
    array.forEach(arrayItem => {
      finalArray[i][Object.keys(arrayItem.data)[i]] = Object.values(arrayItem.data)[i]
    });
  }

  console.log(finalArray)

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