Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

83
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!