If data is an Object, we can use Object.entries
, map
and join
to convert Object into Query String.
Version
ECMAScript 2017
Object.entries
let params = {
a: 1,
b: 2,
c: 3,
};
Object.entries(params)
.map(([k, v]) => `${k}=${v}`)
.join("&"); // ?
Object.entries
: get all keys and values at once into Arraymap
: destructure key and value, and concatenate them to Stringjoin
: join them together with&
Conclusion
- Although we can use
Object.keys
to convert Object into Query String,Object.entries
is more concise