2

I have an json data having property attributes.data. When I console.log(attributes.data) this value I get the result {"uid" : 1} I want to convert this to an array. i.e {"uid" : 1} and so on I want to convert this to form data uid:1. how I will do that in javascripts.

 if (attributes.type == "POST") {
   xmlhttp.open(attributes.type, attributes.url, true);
   xmlhttp.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
   xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
   attributes.data = JSON.stringify(attributes.data);
   xmlhttp.send(attributes.data);
 }
while debug in chrome Network tab i have the form data {"uid" :1} but i want to get this like uid: 1 how do i convert it to that
Muhammad Asif Javed
  • 533
  • 1
  • 7
  • 19

2 Answers2

0

If what you want is to simply convert your object into an array, this would do the job:

var obj = {"key1":"value1","key2":"value2","key32":"value3","key4":"value4"};
var arr = [];
for (key in obj) {
   arr.push(key + ':' + obj[key]);
}

If What you actually want is to post your data as a string using AJAX, then using the given obj object you should just do:

var dataStr = JSON.stringify(obj);
Ronen Cypis
  • 21,182
  • 1
  • 20
  • 25
0

If what you need is to have an array with values like so: ['uid:1', 'key:value', ...]

Then this would work:

var attribute = {
    data: {
      "uid": 1,
      "key2": 'value',
      "key3": 'value'

    }
  },
  key,
  myString = '';

for (key in attribute.data) {

  //this is the line that you want
  myString += "&" + key + ":" + attribute.data[key];
}


//the output of the fist element (there is only one now)
document.querySelector('#result').innerHTML = myString; // "uid:1"
<div id="result"></div>

Hope it helps.

EDIT:

if you want a string with ONLY the "uid" element

var attribute = {
    data: {
      "uid": 1,
    }
  },
  key,
  myString = '';

for (key in attribute.data) {

  //this is the line that you want
  if (key === "uid") {
    myString = key + ":" + attribute.data[key]
  }
}


//the output of the fist element (there is only one now)
document.querySelector('#result').innerHTML = myString; // "uid:1"
<div id="result"></div>
Samuel Tissot
  • 31
  • 1
  • 4
  • please do a favor when use xhr.send(myArray); the form Data in network tab looks like 0:{........} but i want the data like this uid: 1 – Muhammad Asif Javed Oct 22 '15 at 14:28
  • if you just want "uid:1" then use xhr.send(myArray[0]) - where "0" relates to the index of "uid" in the data object. HOWEVER, this implementation is overkill just to get "uid:1" – Samuel Tissot Oct 22 '15 at 15:02
  • I edited both of my answers to show option 1 create a url string where values are separated by "&" // option 2: only get the string for "uid". – Samuel Tissot Oct 22 '15 at 15:23