To retrieve the [key, value] entries and then iterate through them using Array.flatMap()
. If the value
is an array, it gets mapped to an array of "pairs". Otherwise, it simply combines into a "pair". Finally, join the resulting array to form a string:
const createPairs = obj => Object.entries(obj)
.flatMap(([key, value]) =>
Array.isArray(value) ? value.map(v => `${key}=${v}`) : `${key}=${value}`
)
.join(', ');
var result = createPairs({
a: "b",
nums: [1, 2, 3, 4, 5]
});
console.log(result);
The issue with your method is that all keys are combined with all values. Instead, iterate over each key, fetch the corresponding values, and then combine them with the key individually.
Furthermore, it's simpler to store each combination in an array first and then join at the end rather than continuous string concatenation. Directly creating a string would necessitate determining when to add a comma or not, while join automatically adds commas between items.
function createPairs(obj) {
var keys = Object.keys(obj);
var result = [];
for (var i = 0; i < keys.length; i++) {
var k = keys[i];
var values = Array.isArray(obj[k]) ? obj[k] : [obj[k]];
for (var j = 0; j < values.length; j++) {
result.push(k + '=' + values[j]);
}
}
return result.join(', ');
}
var result = createPairs({
a: "b",
nums: [1, 2, 3, 4, 5]
});
console.log(result);