Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Turn a Multiple Array Object into Query String Parameters in JavaScript

I have the following object below with multiple arrays.

{
  "services": [
    {
      "id": "100",
      "name": "PIX"
    },
    {
      "id": "200",
      "name": "Rendimentos"
    }
  ],
  "channels": [
    {
      "id": "300",
      "name": "Chat"
    }
  ]
}

The idea is to generate query strings, something like that.

services=100&services=200&channels=300

I know you can do it with map and join, but I would know if it was with a pure object, now this format below, I'm confused

like image 971
Renan Bessa Avatar asked Apr 30 '26 02:04

Renan Bessa


1 Answers

You can use URLSearchParams() API.

Iterate your data and append key/value pairs or map an entries array to pass to the constructor

I have no idea what determines the expected output you have shown from the data displayed so am using a simpler data structure for demonstration purposes.

You can combine with URL() API to create full url string as shown below also

const data = [
  {name:'foo', value:10},
  {name:'bar', value:20}
]

// Loop and append key/values
const params = new URLSearchParams();
data.forEach(e => params.append(e.name, e.value));
console.log('params:', params.toString());

// Alternate approach passing entries array to constructor
const params2 = new URLSearchParams(data.map(e => [e.name,e.value]));
console.log('params2:',params2.toString())

//Adding to a URL
const url = new URL('http://example.com')
url.search = params

console.log('Full url:',url)

Using the updated array data in question:

const data={services:[{id:"100",name:"PIX"},{id:"200",name:"Rendimentos"}],channels:[{id:"300",name:"Chat"}]};

const entries = [];
Object.entries(data).forEach(([k,arr])=> arr.forEach(({id}) => entries.push([k,id])));

const params = new URLSearchParams(entries);

const url = new URL('http://example.com')
url.search = params;

console.log(url)
like image 173
charlietfl Avatar answered May 01 '26 16:05

charlietfl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!