简体   繁体   中英

Convert javascript object to URL parameters

I realize that fundamentally I'm probably going about this the wrong way so I'm open to any pushes in the right direction.

I'm trying to use the HipChat API to send a notification to a room like so:

https://www.hipchat.com/docs/api/method/rooms/message

I'm trying to build the URL in the example with a js object's parameters, so basically I'm trying to convert this:

var hipChatSettings = {
            format:"json",
            auth_token:token,
            room_id: 1,
            from: "Notifications",
            message: "Message"
        }

To this:

https://api.hipchat.com/v1/rooms/message?format=json&auth_token=token&room_id=1&from=Notifications&message=Message

You should check this jQuery.param function .

 var params = { width:1680, height:1050 }; var str = jQuery.param( params ); console.log(str); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

Object.keys(hipChatSettings).map(function(k) {
    return encodeURIComponent(k) + "=" + encodeURIComponent(hipChatSettings[k]);
}).join('&')
// => "format=json&auth_token=token&room_id=1&from=Notifications&message=Message"

Warning: newish JavaScript. If you want it to work on ancients, shim or rewrite into for .

Something like this could work for you

var str = "?" + Object.keys(hipChatSettings).map(function(prop) {
  return [prop, hipChatSettings[prop]].map(encodeURIComponent).join("=");
}).join("&");

// "?format=json&auth_token=token&room_id=1&from=Notifications&message=Message"

If you can't depend on ECMAScript 5, you can use a simple for loop

var pairs = [];

for (var prop in hipChatSettings) {
  if (hipChatSettings.hasOwnProperty(prop)) {
    var k = encodeURIComponent(prop),
        v = encodeURIComponent(hipChatSettings[prop]);
    pairs.push( k + "=" + v);
  }
}

var str = "?" + pairs.join("&");

ES6 version, can do really nested objects with arrays

encodeURI(getUrlString({a: 1, b: [true, 12.3, "string"]}))

getUrlString (params, keys = [], isArray = false) {
  const p = Object.keys(params).map(key => {
    let val = params[key]

    if ("[object Object]" === Object.prototype.toString.call(val) || Array.isArray(val)) {
      if (Array.isArray(params)) {
        keys.push("")
      } else {
        keys.push(key)
      }
      return getUrlString(val, keys, Array.isArray(val))
    } else {
      let tKey = key

      if (keys.length > 0) {
        const tKeys = isArray ? keys : [...keys, key]
        tKey = tKeys.reduce((str, k) => { return "" === str ? k : `${str}[${k}]` }, "")
      }
      if (isArray) {
        return `${ tKey }[]=${ val }`
      } else {
        return `${ tKey }=${ val }`
      }

    }
  }).join('&')

  keys.pop()
  return p
}

Late to the dance but I quite enjoyed the brevity of this:

  Object.entries(hipChatSettings)
    .map(
      ([key, val]) => `${encodeURIComponent(key)}=${encodeURIComponent(val)}`
    )
    .join("&");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM