12

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
0

8 Answers 8

20

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I tried this let search = Object.assign(urlSearchParams, {number: '5'}); but it didn't seem to work.
i tried code like that in the chrome console and it worked. what browser are you working with? let is a newer keyword so maybe try it with just var. Also, the Object.assign method is not available in IE as per the documentation
Just a note of caution: If you want to retain existing parameters with the same name, append should be used instead of set. URLSearchParams on MDN
4

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

3 Comments

I'm actually using this.http.post so it doesn't work for me :(
you can also use post same way this.http.post('url'+'?myobj='+encodeURIComponent(json))
If I could mark two answers I would mark yours too, but the other answer is better suited to the question :(
4

Super simple answer/example:

// Create:
const params = new URLSearchParams({
  a: 1,
  b: 2
})
// OR
// const params = new URLSearchParams("a=1&b=2")

// Append
params.append('c', 'woohoo') // Note: if c param already exists in params, this will replace it (won't be adding new param if already exists, hence no duplications)

console.log(params.toString())
// Prints: 'a=1&b=2&c=woohoo'

Comments

3

Want to share my answer for Angular2 with the option of sending an Array This is how I use this get function:

this.get('/api/database', {
   'age': [1,2,3,4]
})

And the service is something like:

get(url, _params = {}) {
    let params = this._processParams(_params);

    return this.http.get(url, params).toPromise();
}

_processParams(obj: any) {
        /* Convert this
            { age: [1,2,3] }
           To:
              param.append('age', 1);
              param.append('age', 2);
              param.append('age', 3);
        */        
        let params = new URLSearchParams();

        for (let key in obj) {
            for (let index in obj[key] ) {                
                params.append(key, obj[key][index]);
            }
        }

        return {
            search: params
        };
    }

Comments

3

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' });

1 Comment

is it possible to send an array with that?
2

Here is my approach. We have a simple requirement where the object is only a key value pair where the value might be a string or an array. We haven't found a use case for nested objects.

So let's say we want to convert this object into a query string or vice versa:

const input = {
  ini: 'ini',
  itu: 'itu',
  ayo: ['desc', 'asc'],
}

Then we have two functions to parse & stringify:

function stringify(input) {
  const params = new URLSearchParams();

  for (const key in input) {
    if (Array.isArray(input[key])) {
      input[key].forEach(val => {
        params.append(key + '[]', val)
      })
    } else {
      params.append(key, input[key]);
    }
  }

  return '?' + params.toString();
}
function parse(input) {
  const payload = {};
  const params = new URLSearchParams(input);

  for(let [key, val] of params.entries()) {
    if (key.endsWith('[]')) {
      key = key.replace(/\[\]$/, '');
      if (payload[key]) {
        payload[key].push(val);
      } else {
        payload[key] = [val]
      }
    } else {
      payload[key] = val;
    }
  }

  return payload;
}

So the result should be "?ini=ini&itu=itu&ayo%5B%5D=desc&ayo%5B%5D=asc". This is similar to the array format that is found in this example.

Please note that this might not be battle tested, but for us we don't really have complicated object structure.

Comments

1
const url = new URL('/', location.origin);
console.log(url.href); // https://stackoverflow.com/
Object.entries({this:4,that:1}).forEach((item)=>{ 
// note .set replaces while .append will duplicate params
    url.searchParams.append(...item);
});
console.log(url.href); // https://stackoverflow.com/?this=4&that=1

Comments

-1

It is indeed


import { useUrlState } from 'state-in-url/next';

const form: Form = {
  search: '',
  someObj: undefined
};

type Form = {
  name: string;
  someObj?: { sort: 'abc' | 'desc' }
};

export const useFormState = () => {
  const { urlState, setUrl, reset } = useUrlState(form);

  const handleUpdate = (val) => {
    setUrl({ name: val, someObj: { sort: 'desc' } })
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.