I have a small piece of code that I am trying to do a replacement on. There are two data objects. One is a list of URL's that contain a {variable}, and the other is an object of the replacement values for those variables.
I have created some code to try and get it working but I think there is probably a more efficient way of handling this.
// Content we will look through and replace variables in
let urls = [
'http://www.example.com/{var1}/{var2}',
'http://www.example.com/{var1}/{var4}',
];
// Data used for the replacement
let variables = [{
variable: 'var1',
value: '123'
},
{
variable: 'var2',
value: '456'
},
{
variable: 'var4',
value: '789'
}]
// Will hold the final URLs
let finalURLs = [];
// Loop over all URLS
for (let index = 0; index < urls.length; ++index) {
// Loop over all variables
for (let d = 0; d < data.length; ++d) {
// Set the replaced URL
let u = urls[index].replace('{' + data[d].variable + '}', data[d].value);
finalURLs.push(u);
}
}
// Desired output
finalURLs = [
'http://www.example.com/123/456',
'http://www.example.com/123/789'
]
I'm sure I am way off on this but looking for some pointers on what to do.
datai think it should bevariablesdatainstead ofvariables. There are a few issues, but the question was one of efficiency, and there's really nothing to improve there. He needs two nested loops, regardless if he uses for-loops or map()/forEach() instead. Nothing wrong with it conceptually, he just needs to iron out the bugs.