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

141
Visualizações
Typescript Array restructure

I want to restructure my array, which i retrieved from php, to make it usable with my ngFor.

Currently my array contains ~2700 elements which contain a object with the following data:

name: "Someone"
shift: 3
week: 1
department_name: "somedepartment"

I want change it to array->week->shift->department.name

In JS this would be easy but in Typescript I cant get it working, my actual code looks like:

test(data): void{
//data contains the actual array
let user = [];
for (let entry of data){
  console.log(entry['week']);
  console.log(entry['shift']);
  console.log(entry['department_name']);
  user[entry['week']][entry['shift']][entry['department_name']] = entry;
}
console.log(user);}

console.log returns the first 3 values: 1, 3, "departmentx"

And then returns:

ERROR Error: Uncaught (in promise): TypeError: Cannot read property '3' of undefined TypeError: Cannot read property '3' of undefined

I have read that I have to set the size of the array before, but it will be every time different and later there will be much more information besides the name that get stored.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

If I understood well you want to change the order of the elements within your array, right?

This should work:

    let newArray = [];
    for (let entry in data) {
        let currentObj = {
            [entry.week]: {
              [entry.shift]: entry.department_name
            }
        };
        newArray.push(currentObj);
    }
    console.log(JSON.stringify(newArray));

the output of this would be something like:

   newArray = [
        1: {
            3: "somedepartmentX"
        },
        2: {
            4: "somedepartmentY",
        },
        3: {
            5: "somedepartmentZ",
        },
    ];
over 4 years ago · Santiago Trujillo 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