是否有一个快速和简单的方法来编码JavaScript对象到字符串,我可以通过GET请求传递?
没有jQuery,没有其他框架-只有纯JavaScript:)
是否有一个快速和简单的方法来编码JavaScript对象到字符串,我可以通过GET请求传递?
没有jQuery,没有其他框架-只有纯JavaScript:)
当前回答
如果你想将整个对象作为一个参数传递,例如,?filter={param1: "val1", param2: "val2"}:
const serializeObject = (obj) => {
let objStr = JSON.stringify(obj);
objStr = objStr.replace(/\{/g, encodeURIComponent("{"));
objStr = objStr.replace(/}/g, encodeURIComponent("}"));
objStr = objStr.replace(/:/g, encodeURIComponent(":"));
return objStr;
};
let res = serializeObject({param1: "val1", param2: "val2"});
console.log("serializeObject:", res); //%7B"param1"%3A"val1","param2"%3A"val2"%7D
console.log("serializeObject-decoded:", decodeURIComponent(res)); //{"param1":"val1","param2":"val2"}
其他回答
好吧,似乎每个人都把他的俏皮话写在这里,所以我的是:
const encoded = Object.entries(obj).map(([k, v]) => `${k}=${encodeURIComponent(v)}`).join("&");
您也可以通过使用简单的JavaScript来实现这一点。
const stringData = '?name=Nikhil&surname=Mahirrao&age=30'; const newData= {}; stringData.replace('?', '').split('&').map((value) => { const temp = value.split('='); 新数据[温度[0]] = 温度[1]; }); console.log('stringData: '+stringData); console.log('newData: '); console.log(newData);
let data = {
id:1,
name:'Newuser'
};
const getqueryParam = data => {
let datasize = Object.keys(data).length;
let initial = '?';
Object.keys(data).map(function (key, index) {
initial = initial.concat(`${key}=${data[key]}`);
index != datasize - 1 && (initial = initial.concat('&'));
});
console.log(initial, 'MyqueryString');
return initial;
};
console.log(getqueryParam(data))//You can get the query string here
If you have baseUrl means to get full query use
baseUrl concat (getqueryParam(数据)。
是这样的:
Serialize =函数(obj) { Var STR = []; For (var p in obj) if (obj.hasOwnProperty(p)) { str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]))); } 返回str.join(“&”); } console.log(序列化({ Foo:“你好”, 栏:“100%” })); / / foo =你好% 20 there&bar 25 = 100%
它还转换递归对象(使用PHP“数组”符号表示查询字符串):
serialize = function(obj, prefix) { var str = [], p; for (p in obj) { if (obj.hasOwnProperty(p)) { var k = prefix ? prefix + "[" + p + "]" : p, v = obj[p]; str.push((v !== null && typeof v === "object") ? serialize(v, k) : encodeURIComponent(k) + "=" + encodeURIComponent(v)); } } return str.join("&"); } console.log(serialize({ foo: "hi there", bar: { blah: 123, quux: [1, 2, 3] } })); // foo=hi%20there&bar%5Bblah%5D=123&bar%5Bquux%5D%5B0%5D=1&bar%5Bquux%5D%5B1%5D=2&bar%5Bquux%5D%5B2%5D=3
我为此写了一个包:object-query-string:)
它支持嵌套对象、数组、自定义编码函数等。它是轻量级的,不支持jquery。
// TypeScript
import { queryString } from 'object-query-string';
// Node.js
const { queryString } = require("object-query-string");
const query = queryString({
filter: {
brands: ["Audi"],
models: ["A4", "A6", "A8"],
accidentFree: true
},
sort: 'mileage'
});
返回
filter[brands][]=Audi&filter[models][]=A4&filter[models][]=A6&filter[models][]=A8&filter[accidentFree]=true&sort=milage