Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using json objects in URLSearchParams

Is it possible to somehow append json objects onto a URLSearchParams object?

So instead of:

urlSearchParams.append('search', 'person');

it's:

urlSearchParams.append({search: "person"});


My answer courtesy of Darshak Gajjar's answer

Can use json objects via this way:

let test_this = [{"search": "person"}, { search: "another person"}];
var json = JSON.stringify(test_this);
urlSearchParams.append("myobj", json);

return this.http.post(this.post_url, urlSearchParams, options) //options being your own RequestOptions
like image 239
A. L Avatar asked Dec 14 '16 05:12

A. L


3 Answers

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

Something like this might work urlSearchParams = Object.assign(urlSearchParams, {search: "person"});

EDIT: Alternate solution using vanilla javascript. Also, I thought URLSearchParams was just a normal js object, but in fact you have to use get, set and append to access properties.

var params = new URLSearchParams("a=apple&b=balloon");
var parametersToAdd = {c: "car", d: "duck"};
for(key in parametersToAdd)
  params.append(key, parametersToAdd[key]);

console.log(params.get('c'));
console.log(params.get('d'));
  

EDIT bis: .append() supports to re-use the same key/parameter name, while .set() would have overwritten a previous value.

like image 56
murtuza Avatar answered Oct 17 '22 15:10

murtuza


May be using below code you can pass entire json object in URL Search param

var json = JSON.stringify(myObj);

this.http.get('url'+'?myobj='+encodeURIComponent(json))
like image 21
Darshak Avatar answered Oct 17 '22 16:10

Darshak


There's no API for that. You just need to enumerate over the properties and append them manually, for example using the following function:

function appendParams(params: URLSearchParams, obj: any) {
  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      params.append(key, obj[key])
    }
  }
}

appendParams(urlSearchParams, { search: 'person' });
like image 4
Paul Samsotha Avatar answered Oct 17 '22 16:10

Paul Samsotha