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

Viewed 1998

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

2 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)

Looks like you're hung up on trying to iterate an object with map() or join(), which you can't do directly. Instead you can use Object.entries to convert the object into an array and iterate that. Since there is a nested map() you can flat() it before join()

let obj = {
  "services": [{
      "id": "100",
      "name": "PIX"
    },
    {
      "id": "200",
      "name": "Rendimentos"
    }
  ],
  "channels": [{
    "id": "300",
    "name": "Chat"
  }]
}
let queryString = Object.entries(obj).map(s => s[1].map(e => `${s[0]}=${e.id}`)).flat().join('&')
console.log(queryString)

Related