0

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! :)

1 Answer 1

2

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);

Sign up to request clarification or add additional context in comments.

4 Comments

Nice!! Aww I'm new to JS but how amazing it its!! Thank you!!
@danh thanks for the input! I've updated the answer and now I wait for your upvote :-)
Guys you talk about upvoting and things like that and to me this is a journey of discovery and I love to realise JS can do things in so many different ways! :) thank you to all!
:-) plus one. note that param => ({ object }) works in every dialect that supports fat arrow functions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.