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! :)
asked Feb 23, 2020 at 21:16
Guillermo Brachetta
4,9935 gold badges29 silver badges45 bronze badges
1 Answer 1
Of course but you will need the alphabet somewhere. Maybe .map() is the cleanest solution
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);
answered Feb 23, 2020 at 21:21
caramba
22.5k20 gold badges94 silver badges134 bronze badges
Sign up to request clarification or add additional context in comments.
4 Comments
Guillermo Brachetta
Nice!! Aww I'm new to JS but how amazing it its!! Thank you!!
caramba
@danh thanks for the input! I've updated the answer and now I wait for your upvote :-)
Guillermo Brachetta
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!
danh
:-) plus one. note that
param => ({ object }) works in every dialect that supports fat arrow functions.lang-js