Last active
September 28, 2022 07:19
-
-
Save TravelingTechGuy/32454b95a50d296912b9 to your computer and use it in GitHub Desktop.
JSON object to query string (using underscore/lodash)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var objectToQueryString = function(obj) { | |
var qs = _.reduce(obj, function(result, value, key) { | |
return (!_.isNull(value) && !_.isUndefined(value)) ? (result += key + '=' + value + '&') : result; | |
}, '').slice(0, -1); | |
return qs; | |
}; |
Perfect ! @TravelingTechGuy
Using _.forOwn instead of _.reduce (null checks removed):
const obj = {
a: 1,
b: 2,
c: [3, 4, 5, null, 7]
};
const objectToQueryString = obj => {
const results = [];
_.forOwn(obj, (value, key) => {
if (Array.isArray(value)) {
_.forOwn(value, value => {
results.push(`${key}=${value}`);
});
} else {
results.push(`${key}=${value}`);
}
});
return results.join('&');
};
console.log(objectToQueryString(obj));
_.map(obj, (value, key) => `${key}=${value}`).join('&')
Here's some other options that don't require lodash.
'use strict'
// Other ways APIs implement URLSearchParams. Not my own, but I can't find the original source.
// https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/URLSearchParams
var obj = {
a: 1,
b: 2,
c: [3, 4, 5, null, 7],
foo: {bar: 'baz'}
};
function URLSearchParamsWithArrayBrackets(obj, prefix) {
let str = [],
p;
for (p in obj) {
if (obj.hasOwnProperty(p)) {
let k = prefix ? prefix + "[]" : p,
v = obj[p];
str.push(
v !== null && typeof v === "object"
? URLSearchParamsWithArrayBrackets(v, k)
: encodeURIComponent(k) + "=" + encodeURIComponent(v)
);
}
}
return str.join("&");
}
function URLSearchParamsWithArrayIndices(obj, prefix) {
let str = [],
p;
for (p in obj) {
if (obj.hasOwnProperty(p)) {
let k = prefix ? prefix + "[" + p + "]" : p,
v = obj[p];
str.push(
v !== null && typeof v === "object"
? URLSearchParamsWithArrayIndices(v, k)
: encodeURIComponent(k) + "=" + encodeURIComponent(v)
);
}
}
return str.join("&");
}
var params;
params = new URLSearchParams(obj).toString(); // 'a=1&b=2&c=3%2C4%2C5%2C%2C7&foo=%5Bobject+Object%5D'
params = URLSearchParamsWithArrayBrackets(obj); // 'a=1&b=2&c%5B%5D=3&c%5B%5D=4&c%5B%5D=5&c%5B%5D=null&c%5B%5D=7&foo%5B%5D=baz'
params = URLSearchParamsWithArrayIndices(obj); // 'a=1&b=2&c%5B0%5D=3&c%5B1%5D=4&c%5B2%5D=5&c%5B3%5D=null&c%5B4%5D=7&foo%5Bbar%5D=baz'
From https://gist.github.com/3ch01c/37b7a292c744628f189eeabc917a309b/
Object.entries(someobject).reduce((result, item)=>{return result += ${item[0]}=${item[1]}&
}, '').slice(0, -1)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
!_.isNull(value) && !_.isUndefined(value)
could be simpler as!_.isNil(value)