Search code examples
javascriptobject

renaming object with value from string array


I am trying to use a value from an array of strings in place of the name of my object "midgaard" I tried both to change it to scene[0] and scene[0]. but nothing works. I dont understand the logic behind clearly. what can i do to replace midgard with a value from the array?

const whatDay = ["mon", "tue", "wed"];

const scene = ["midgard"];

function playingWhen(whatDay, scene) {
  let arr = [];
  for (let x = 0; x < whatDay.length; x++) {
    for (let i = 0; i < scene[0][whatDay[x]].length; i++) { //<-----
      console.log(i, midgard[whatDay[x]][i].act);
      arr.push({ [whatDay[x]]: midgard[whatDay[x]][i].act });
    }
  }
  console.log(arr);
}

playingWhen(whatDay);

const midgard = {
  mon: [
    { start: "00:00", end: "02:00", act: "Barrows Group", cancelled: true },
    { start: "02:00", end: "04:00", act: "break" },
  ],
  tue: [
    { start: "00:00", end: "02:00", act: "Bartell - Cummerata", cancelled: true },
    { start: "02:00", end: "04:00", act: "break" },
  ],
  wed: [
    { start: "00:00", end: "02:00", act: "A Perfect Circle" },
    { start: "02:00", end: "04:00", act: "break" },
  ],
};

Solution

  • you can make an object which contains all the scenes, something like that:

    const scenes = {
    midgard :{
      mon: [
        { start: "00:00", end: "02:00", act: "Barrows Group", cancelled: true },
        { start: "02:00", end: "04:00", act: "break" },
      ],
      tue: [
        { start: "00:00", end: "02:00", act: "Bartell - Cummerata", cancelled: true },
        { start: "02:00", end: "04:00", act: "break" },
      ],
      wed: [
        { start: "00:00", end: "02:00", act: "A Perfect Circle" },
        { start: "02:00", end: "04:00", act: "break" },
      ],
    }
    
    }
    

    and then you can access it like that:

    scenes[scene[0]]
    

    it will make your code harder to read, try using Object Destructuring