Search code examples
javascriptjqueryarraysjsonjavascript-objects

Having trouble turning my Javascript Object into a parameter string


I have an object with the following data structure below. I am trying to turn this object into a parameter string by doing the following below.

When my code snippet is run in the debugger I don't see an error in the console but it submits the form prematurely for some reason and in the URL I can see my params being posted and stops the rest of my script. The Object,keys does not look right and is producing the following int he debugger.

keys
(273) ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", * "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "90", "91", "92", "9 3", "94", "95", "96", "97", "98", "99", CJ
•   [0  99]
•   [100    199]
•   [200    272]
length: 273
•       proto   : Array(0)

What is the best way to take the object below and turn it into a parameter string to send via ajax?

I am expecting to return a parameter string like the following ip=111.111.111.111&hostname=rr.com&city=mycity and so forth.

below is my ipinfo object

{"ip":"111.111.111.111","hostname":"rr.com","city":"MyCity","region":"Ohio","country":"US","loc":"41.34.23","org":"Inc","postal":"1234","timezone":"America/New_York","readme":"https://www.google.com"}"

    var myKeys = Object.keys(ipinfo);
        var queryString = "";
        for (var i = 0; i < myKeys.length; i++) {
            var theKey = ipinfo[i];
            if (queryString !== "") queryString += "&";
            queryString += theKey + "=" + JSON.Stringify(ipinfo[theKey]);
        }

Solution

  • It seens like you need to JSON.parse() your object first. Also you can try:

    Object.entries(JSON.parse(ipinfo)).map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`).join('&')