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

85
Visualizações
Build nested Object/Array with jquery

I'm trying to build a javascript object from the inputs of a dynamic form. This is what I'm trying to do:

fieldTickets = [];
thisWeek = randomDateOnSunday;
weekDay = randomWeekDayWithinTheWeek;
fieldTickets[thisWeek]['days'][weekDay]['fieldTechs'].push({name: fieldTechName});

As you can see, I have some keys that are dynamic variables and some that are defined ('days' and 'fieldTechs' are always the same, but the week and weekday will change). Unfortunately every time I try to run this, even on fiddles, it gives me Cannot read properties of undefined (reading 'days') as an error. I've been dealing with this for hours and can't figure it out.

How does one build a nested array/object with dynamic keys?

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

0

i thought that it would create it automatically if it didn't exist by using that syntax...obviously I'm wrong but is there another shorter way than a ton of if exists statements?

JavaScript will not create it automatically, but can do it without if, try something like below

const thisWeek = '12'; //randomDateOnSunday;
const weekDay = 'Sunday'; // randomWeekDayWithinTheWeek;

fieldTickets = {
  [thisWeek]: {
    days: {
      [weekDay]: {
        fieldTechs: []
      }
    }
  }
};

console.log('fieldTickets:', fieldTickets);

// pushing 
fieldTickets[thisWeek]['days'][weekDay]['fieldTechs'].push({
  name: "Hello"
});

// pushing again
fieldTickets[thisWeek]['days'][weekDay]['fieldTechs'].push({
  name: "World"
});
console.log('fieldTickets 2:', fieldTickets);

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