[英]Convert a nested object/ associative array into a query string using JavaScript
I want to use JavaScript to convert an object into a query string.我想使用 JavaScript 将对象转换为查询字符串。
For example, I want to convert:例如,我想转换:
{
a: 'hello',
b: {
b1: 'my',
b2: 'friend',
b3: {
c: 90
}
}
}
to:到:
?a=hello&b%5Bb1%5D=my&b%5Bb2%5D=friend&b%5Bb3%5D%5Bc%5D=90
I have found quite a few answers to this here: Flatten a javascript object to pass as querystring , but they don't seem to deal with the issue of associative arrays (or objects within objects).我在这里找到了很多答案: Flatten a javascript object to pass as querystring ,但它们似乎没有处理关联数组(或对象中的对象)的问题。
I found a good answer for JQuery which works fine by using jQuery.param
, but i would like an answer using either native JS or Underscore.js.我找到了一个很好的 JQuery 答案,通过使用jQuery.param
可以很好地工作,但我想要一个使用本机 JS 或 Underscore.js 的答案。
How can I do this?我怎样才能做到这一点?
I highly recommend not trying to reinvent existing wheels.我强烈建议不要尝试重新发明现有的轮子。 Your own implementation is probably going to be much less flexible and way more error-prone (have you thought about encoding the query string parameters correctly, for instance?) Instead, take a look at the query-string module.您自己的实现可能会更不灵活并且更容易出错(例如,您是否考虑过正确编码查询字符串参数?)相反,请查看查询字符串模块。
you can do this:你可以这样做:
let obj = {
a: 'hello',
b: {
b1: 'my',
b2: 'friend',
b3: {
c: 90
}
}
}
function getQueryString(obj, encode) {
function getPathToObj(obj, path = []) {
let result = [];
for (let key in obj) {
if (!obj.hasOwnProperty(key)) return;
//deep copy
let newPath = path.slice();
newPath.push(key);
let everyPath = [];
if (typeof obj[key] === "object") {
everyPath = getPathToObj(obj[key], newPath);
} else {
everyPath.push({
path: newPath,
val: obj[key]
});
}
everyPath.map((item) => result.push(item))
}
return result;
}
function composeQueryString(paths) {
let result = "";
paths.map((item) => {
let pathString = "";
if (item.path.length > 1) {
pathString = item.path.reduce((a, b, index) => {
return a + '['+ b +']';
})
} else {
pathString = item.path[0];
}
if (result) {
pathString = "&" + pathString + '=' + item.val;
} else {
pathString = "?" + pathString + '=' + item.val;
}
result += pathString;
});
return result;
}
const str = composeQueryString(getPathToObj(obj));
return encode === true ? encodeURI(str) : str;
}
console.log(getQueryString(obj, true));
get: ?a=hello&b%5Bb1%5D=my&b%5Bb2%5D=friend&b%5Bb3%5D%5Bc%5D=90得到:?a=hello&b%5Bb1%5D=my&b%5Bb2%5D=friend&b%5Bb3%5D%5Bc%5D=90
Axios
you can easily achieve this:使用Axios
您可以轻松实现这一目标: const instance = axios.create({ url: '/user', baseUrl: 'https://my-api-server' }); const config = { params: { a: 'hello', b: { b1: 'my', b2: 'friend', b3: { c: 90 } } } } const uri = instance.getUri(config) document.write(uri)
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
Good Luck...祝你好运...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.