const template = {
example: {
simple: ['Hey', 'Origami'],
extra: ['Its me', 'Dotcom']
}
}
I want to join each element of template.example.simple & template.example.extra together.
So the results would be:
['Hey', 'Origami', 'Hey Its me', 'Hey Dotcom', 'Origami Its me', 'Origami Dotcom']
In order to accomplish that, what I'm doing right now is:
const template = {
example: {
simple: ['Hey', 'Origami'],
extra: ['Its me', 'Dotcom']
}
}
const example = template.example.simple;
template.example.simple.forEach((s) => {
let extra = s;
template.example.extra.forEach((a) => {
extra += ` ${a}`;
example.push(extra);
extra = s;
});
});
console.log(example);
//example = ['Hey', 'Origami', 'Hey Its me', 'Hey Dotcom', 'Origami Its me', 'Origami Dotcom']
So my question is if there's a simpler method of accomplishing this, and how would you improve this?
Simpler is a very relative term. I would not call this method simpler/easier to read, but for the sake of giving alternatives, this one liner should do the trick. It uses map to select both the original value from simple and an extra map to get simple and extra together (and the spread operator ... to flatten them)
const template = {
example: {
simple: ['Hey', 'Origami'],
extra: ['Its me', 'Dotcom']
}
};
const example = Array.prototype.concat(...template.example.simple.map(p=>[p,...template.example.extra.map(e=>p + ' ' + e)]));
console.log(example);