I was looking for a similar JavaScript method for http_build_query but did not find but create my own and here I am a bit confused to decide the right approach.
Here is the problem. I have an object of params and need to create query string to append with URL with help of encodeURIComponent:
const params = {
"name": ["alpha &", "beta"],
"id": ["one", "&two=2"],
"from": 1533735971000,
"to": 1533822371147,
"status": true
};
Now there are two approaches when there is an array of strings are there. I name them pre-encode and post-encode for now.
pre-encode
Apply encodeURIComponent to individual items and then join all items.
const params = {
"name": ["alpha &", "beta"],
"id": ["one", "&two=2"],
"from": 1533735971000,
"to": 1533822371147,
"status": true
};
const output = Object.entries(params).map((pair) => {
const [key, val] = pair;
if (val instanceof Array && val.length > 0) {
let pre_encode = val.map(encodeURIComponent).join(',');
console.log({pre_encode});
const pre_qs = `${encodeURIComponent(key)}=${pre_encode}`;
console.log({pre_qs})
return pre_qs;
} else {
return pair.map(encodeURIComponent).join('=');
}
}).join('&');
console.log({output});
Output
"name=alpha%20%26,beta&id=one,%26two%3D2&from=1533735971000&to=1533822371147&status=true"
post-encode
First, join all items then apply encodeURIComponent.
const params = {
"name": ["alpha &", "beta"],
"id": ["one", "&two=2"],
"from": 1533735971000,
"to": 1533822371147,
"status": true
};
const output = Object.entries(params).map((pair) => {
const [key, val] = pair;
if (val instanceof Array && val.length > 0) {
let post_encode = encodeURIComponent(val.join(','));
console.log({post_encode});
const post_qs = `${encodeURIComponent(key)}=${post_encode}`;
console.log({post_qs})
return post_qs;
} else {
return pair.map(encodeURIComponent).join('=');
}
}).join('&');
console.log({output});
Output
"name=alpha%20%26%2Cbeta&id=one%2C%26two%3D2&from=1533735971000&to=1533822371147&status=true"
Which approach is the more efficient and right and how to handle null and undefined values?