I am trying to turn an array of JavaScript objects into a URL string with params, as seen below:
const objects = [{
firstName: "John",
lastName: "Doe",
age: 46
},
{
country: "France",
lastName: "Paris"
}
]
let entry_arr = [];
objects.forEach(obj => {
Object.entries(obj).forEach(entry => {
entry_arr.push(entry.join('='));
});
});
let entry_str = entry_arr.join('&');
console.log(entry_str);
By all appearances, the above code works. There is a problem though.
The problem
As you can see, I have 2 nested forEach loops. For better performance, I wish I knew how to avoid this nesting and instead use only one forEach loop.
new URLSearchParams(Object.assign({}, ...objects)).toString(). But, this will overwrite the duplicate parameterlastName. This will also handle special characters in values.