Guillermo Brachetta
Guillermo Brachetta

Reputation: 4745

Building an array of objects with a loop

Would it be possible to build the following variable with a loop?

let mp3list = [
  {
    name: "Minuetto A",
    path: "assets/music/minuettoA.mp3"
  },
  {
    name: "Minuetto B",
    path: "assets/music/minuettoB.mp3"
  },
  {
    name: "Minuetto C",
    path: "assets/music/minuettoC.mp3"
  },
  {
    name: "Minuetto D",
    path: "assets/music/minuettoD.mp3"
  },
  {
    name: "Minuetto E",
    path: "assets/music/minuettoE.mp3"
  },
  {
    name: "Minuetto F",
    path: "assets/music/minuettoF.mp3"
  } // etc
];

It looks so 'patterned' that I guess there should be a way! I'm curious to know! :)

Upvotes: 0

Views: 37

Answers (1)

caramba
caramba

Reputation: 22480

Of course but you will need the alphabet somewhere. Maybe .map() is the cleanest solution

Array.prototype.map()

let alphabet = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K']; // and so on

let mp3list = alphabet.map( item => {
    return {
      name: `Minuetto ${item}`,
      path: `assets/music/minuetto${item}.mp3`
    };
});
console.log(mp3list);

or with ES6 Array.prototype.forEach()

let alphabet = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K']; // and so on
let mp3list = [];

alphabet.forEach( item => {
  mp3list.push(
    {
      name: `Minuetto ${item}`,
      path: `assets/music/minuetto${item}.mp3`
    }
  );
});
console.log(mp3list);

or old school Array.prototype.forEach() with string concatenation

let alphabet = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K']; // and so on
let mp3list = [];
alphabet.forEach(function(item){
  mp3list.push(
    {
      name: "Minuetto " + item,
      path: "assets/music/minuetto"+item+".mp3"
    }
  );
});
console.log(mp3list);

Upvotes: 2

Related Questions