Home > Back-end >  Build nested Object/Array with jquery
Build nested Object/Array with jquery

Time:11-07

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?

CodePudding user response:

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);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related