2

I have the following variables in javascript

var domain= http://example.com/api/v1/purchases/get_purchases.json?
var header = 'df0a96ddbe1ada9fda4b1ed9b02cf67c'
var params = {
                   search:{
                         status_eq: 'frozen',
                         email_eq: '[email protected]',
                         phone_number_eq: ''
                   }
                  }
var api_string = domain + header + params;

I need output of api_string to be:

http://example.com/api/v1/purchases/get_purchases.json?headers%5B_token%5D=df0a96ddbe1ada9fda4b1ed9b02cf67c&search%5Bemail_eq%[email protected]&search%5Bphone_number_eq%5D=12345&search%5Bstatus_eq%5D=frozen

I tried JSON.stringify, encodeURI, encodeURIComponent but it doesnt work as expected.

I need to use this api_string in fetch function of react-native.

1

3 Answers 3

1

You could use a serializing function, like so:

serialize = function(obj, prefix) {
  var str = [], p;
  for(p in obj) {
    if (obj.hasOwnProperty(p)) {
      var k = prefix ? prefix + "[" + p + "]" : p, v = obj[p];
      str.push((v !== null && typeof v === "object") ?
        serialize(v, k) :
        encodeURIComponent(k) + "=" + encodeURIComponent(v));
    }
  }
  return str.join("&");
}

console.log(serialize(params));

Gives:

search%5Bstatus_eq%5D=frozen&search%5Bemail_eq%5D=a%40a.com&search%5Bphone_number_eq%5D=`
Sign up to request clarification or add additional context in comments.

4 Comments

yah this works fine.. but do we have someother npm, javascript function or so ?
@subha if you are looking for a npm function I think my answer might suit you
I dont understand your question @subha - "but do we have someother npm, javascript function or so ?" - could you elaborate?
@Stuart I meant to say I would prefer to use some existing libraries that I can rely for all edge cases ...
0

Good news, string concatination can be done with just the + operator. So you can do something like this

let result = domain + "headers%5B_token%5D=" + header + "&search%5Bemail_eq%5D=" + params.search.eqmail_eq

(obviously extend this for the rest of the parameters, assuming you only have those three params ever)

1 Comment

im trying to write a function that will handle params of any type.. so this wil not be helpful. Thankyou for ur help anyway...
0

Have you tried using the npm package url ?

This is an example of how it works:

    const url = require('url')

    let my_url = url.format({
          hostname: "mydomain.com",
          protocol: "http",
          query: {status_eq: 'frozen', email_eq: '[email protected]',},
          pathname: '/my/path'
    })

here is the documentation if you need to know more about how it works.

WARNING

url.format takes in an object of the parameters you want to send to the server. Make sure that if one of the parameters you want to pass is an object you JSON.stringify it before adding it to the query. Here is a stackoverflow question that explains it.

5 Comments

mmm, weird, could you comment with the object you are trying to format?
this is the object im trying.. var params = { search:{ status_eq: '', email_eq: '[email protected]', phone_number_eq: '' } }
I see what is going on. You are passing an object as a value. In that case you need to JSON.stringify the object that you pass to search. I will make an update to my answer in case more people are having this problem!
The params object is result of an API call.. I will not know the levels of nesting in it.. how do I handle this?
JSON.stringify will take care of any nested level. You need to call it on the first layer. So in your case whatever you pass to search.

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.