Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Udev's avatar
Level 2

query array to object

I have a query ?page=1&filter[name]=white%20t-shirt&filter[attributes][color][]=red&filter[attributes][color][]=blue&filter[attributes][size]=xl

how can I convert it to a js object

filter:{
    name:'white t-shirt',
    attributes:{
        color:['red','blue'],
        size:'xl'
}

after conversion and making some changes: convert back to query

0 likes
6 replies
vincent15000's avatar

Perhaps with this ?

const url = "https://yourdomain.com?page=1&filter[name]=white%20t-shirt&filter[attributes][color][]=red&filter[attributes][color][]=blue&filter[attributes][size]=xl";
const urlSearchParams = new URLSearchParams(url);
const params = Object.fromEntries(urlSearchParams.entries());
1 like
Udev's avatar
Level 2

@vincent15000 did not work. Was thinking of writing some messy function for this but realised you can do this :

const filter = reactive({
	name: route.query['filter[name]']  ?? '',
	attributes:{
		color: route.query['filter[attributes][color][]'] ?? [],
		size: route.query['filter[attributes][size]'] ?? '',
}})

then I can use it like this

<input type="text" v-model="filter.name">

To convert back, I couldn't avoid this messy function

let query = '?page='+pageno+objectToQuery('filter',filter);

const objectToQuery = (field, obj, prefix = null) => {
		let query = "";
		if (obj) {
			let keys = Object.keys(obj);
			keys.forEach((key) => {
				if (Array.isArray(obj[key])) {
					obj[key].forEach((e) => {
						if (e != null) query += '&'+field + (prefix ?? "") + "[" + key + "]" + "[]=" + e;
					});
				} else if (typeof obj[key] === "object" && !Array.isArray(obj[key])) {
					query += objectToQuery(field, obj[key], (prefix ?? "") + "[" + key + "]");
				} else {
					if (obj[key] != null) query += '&'+field + (prefix ?? "") + "[" + key + "]=" + obj[key];
				}
			});
		}
		return query;
	};

is there a better way to convert the object back to a query string?

1 like
Udev's avatar
Level 2

@vincent15000 notice the red color is cut when you do it like this, i.e. filter[attributes][color][]=red

1 like
Udev's avatar
Level 2

Im using a vue framework(nuxt) where I have access to route object. then I can get the colors as route.query['filter[attributes][color][]'] which returns an array ['red','blue'] . not sure how the route works in the background. maybe it uses URLSearchParams.

1 like

Please or to participate in this conversation.