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

88
Visualizações
Is there a clean way to parse an array of Objects?

Sorry I don't know how to word that title.
I want to transform the following data structure :

raw = [
   {'id': 1, 'tilt': [tilt1_1, ..., tilt9_1]},
   {'id': 2, 'tilt': [tilt1_2, ..., tilt9_2]},
   ...
   {'id': n, 'tilt': [tilt1_n, ..., tilt9_n]},
];

Into :

tilts = [
    [tilt1_1, ..., tilt1_n],
    [tilt2_1, ..., tilt2_n],
    ...
    [tilt9_1, ..., tilt9_n],
];

I have the following working solution:

tilts = [[], [], [], [], [], [], [], [], []];
for (let i = 0; i < raw.length; i++) {
  for (let j = 0; j < tilts.length; j++) {
    tilts[j].push(raw[i]['tilt'][j]);
  }
}

Is there a cleaner or more idiomatic way of achieving this ?

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

0

The thing you're asking for is an array transpose, it can be done in this way:

[
    { 'id': 1, 'tilt': [1.1,1.2,1.3] },
    { 'id': 2, 'tilt': [2.1,2.2,2.3] },
    { 'id': 3, 'tilt': [3.1,3.2,3.3] },
].map(e => e.tilt)                            // isolate the tilt property
 .map((_, i, arr) => arr.map(row => row[i])); // transpose the array

The result will be:

[
    [1.1, 2.1, 3.1], 
    [1.2, 2.2, 3.2], 
    [1.3, 2.3, 3.3]
]


Edit:

If elements are missing in the array, you can filter them out:

[
    { 'id': 1, 'tilt': [1.1] },
    { 'id': 2, 'tilt': [2.1, 2.2] },
    { 'id': 3, 'tilt': [3.1, 3.2, 3.3] },
].map(e => e.tilt)
 .map((_, i, arr) => arr.map((row) => row[i]).filter(e => e))

// result
[
    [1.1], 
    [2.1, 2.2], 
    [3.1, 3.2, 3.3]
]
about 4 years ago · Juan Pablo Isaza Relatório

0

let tilts = raw.map( ( val ) => val.tilt );

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