是否有一个快速和简单的方法来编码JavaScript对象到字符串,我可以通过GET请求传递?
没有jQuery,没有其他框架-只有纯JavaScript:)
是否有一个快速和简单的方法来编码JavaScript对象到字符串,我可以通过GET请求传递?
没有jQuery,没有其他框架-只有纯JavaScript:)
当前回答
单行转换对象为查询字符串,以防有人再次需要它:
let Objs = { a: 'obejct-a', b: 'object-b' }
Object.keys(objs).map(key => key + '=' + objs[key]).join('&')
// The result will be a=object-a&b=object-b
其他回答
可以将具有未定义属性的对象传递给此函数。如果属性存在,它将被转换为查询字符串并返回查询字符串。
函数convertToQueryString(props) { const objQueryString ={…道具}; for (objQueryString中的const键){ If (!key) { 删除objQueryString(例子); } } const params = JSON.stringify(objQueryString); Const qs =参数 .replace (/[/''""{}]/ 克,”) .replace (/ [:] / g, ' = ') .replace (/, / g, ' & '); console.log (qs) 返回qs; } convertToQueryString({order: undefined, limit: 5, page: 1})
参考答案@user187291,添加“isArray”作为参数,使要转换的JSON嵌套数组。
data : {
staffId : "00000001",
Detail : [ {
"identityId" : "123456"
}, {
"identityId" : "654321"
} ],
}
要得到结果:
staffId=00000001&Detail[0].identityId=123456&Detail[1].identityId=654321
serialize = function(obj, prefix, isArray) {
var str = [],p = 0;
for (p in obj) {
if (obj.hasOwnProperty(p)) {
var k, v;
if (isArray)
k = prefix ? prefix + "[" + p + "]" : p, v = obj[p];
else
k = prefix ? prefix + "." + p + "" : p, v = obj[p];
if (v !== null && typeof v === "object") {
if (Array.isArray(v)) {
serialize(v, k, true);
} else {
serialize(v, k, false);
}
} else {
var query = k + "=" + v;
str.push(query);
}
}
}
return str.join("&");
};
serialize(data, "prefix", false);
好吧,这是一个旧的帖子,但我正面临这个问题,我已经找到了我的个人解决方案。也许可以帮助别人…
function objToQueryString(obj){
var k = Object.keys(obj);
var s = "";
for(var i=0;i<k.length;i++) {
s += k[i] + "=" + encodeURIComponent(obj[k[i]]);
if (i != k.length -1) s += "&";
}
return s;
};
ES6解决方案用于JavaScript对象的查询字符串编码
const params = {
a: 1,
b: 'query stringify',
c: null,
d: undefined,
f: '',
g: { foo: 1, bar: 2 },
h: ['Winterfell', 'Westeros', 'Braavos'],
i: { first: { second: { third: 3 }}}
}
static toQueryString(params = {}, prefix) {
const query = Object.keys(params).map((k) => {
let key = k;
const value = params[key];
if (!value && (value === null || value === undefined || isNaN(value))) {
value = '';
}
switch (params.constructor) {
case Array:
key = `${prefix}[]`;
break;
case Object:
key = (prefix ? `${prefix}[${key}]` : key);
break;
}
if (typeof value === 'object') {
return this.toQueryString(value, key); // for nested objects
}
return `${key}=${encodeURIComponent(value)}`;
});
return query.join('&');
}
toQueryString (params)
"a=1&b=query%20stringify&c=&d=&f=&g[foo]=1&g[bar]=2&h[]=Winterfell&h[]=Westeros&h[]=Braavos&i[first][second][third]=3"
PHP符号的TypeScript版本(没有URL转义版本)
/**
* Converts an object into a Cookie-like string.
* @param toSerialize object or array to be serialized
* @param prefix used in deep objects to describe the final query parameter
* @returns ampersand separated key=value pairs
*
* Example:
* ```js
* serialize({hello:[{world: "nice"}]}); // outputs "hello[0][world]=nice"
* ```
* ---
* Adapted to TS from a StackOverflow answer https://stackoverflow.com/a/1714899/4537906
*/
const serialize = (toSerialize: unknown = {}, prefix?: string) => {
const keyValuePairs = [];
Object.keys(toSerialize).forEach((attribute) => {
if (Object.prototype.hasOwnProperty.call(toSerialize, attribute)) {
const key = prefix ? `${prefix}[${attribute}]` : attribute;
const value = toSerialize[attribute];
const toBePushed =
value !== null && typeof value === "object"
? serialize(value, key)
: `${key}=${value}`;
keyValuePairs.push(toBePushed);
}
});
return keyValuePairs.join("&");
};