1

Im updating many fields using ajax. My server is getting a row from the database then I am JSON encoding the row and sending this as my xmlhttp.responseText.

The response text is of the form

 {"JobCardNum":5063,"IssueTo":"MachineShop","Priority":"High" ...lots of data}

In the browser I then JSON parse the response text and then begin the long process of updating the values like so:

 var obj = JSON.parse(info);
            document.getElementById("JobCardNum").value = obj.JobCardNum;
            document.getElementById("IssueTo").value = obj.IssueTo;
            document.getElementById("MachineShop").value = obj.MachineShop; 
....... lots of similar statements

As the element id matches the column names I though there might be a way to loop through my JavaScript object and set all my values. Any Ideas?

Connor Bishop
  • 921
  • 1
  • 12
  • 21
  • 1
    Are u looking for a way to loop javascript object? [This question](http://stackoverflow.com/questions/684672/how-do-i-loop-through-or-enumerate-a-javascript-object) may be of some help. – MMhunter Jul 09 '16 at 08:17

2 Answers2

2

This code should iterate over your json object and update the values.

for (var key in p) {
  if (p.hasOwnProperty(key)) {
    var el = document.getElementById(key);
    if(el) el.value = p[key];
  }
}
Shlomi Haver
  • 954
  • 9
  • 14
1

The solution using Object.keys and Array.forEach functions:

var obj = JSON.parse(info);

Object.keys(obj).forEach(function(id){
    var el = document.getElementById(id);
    if (el) el.value = obj[id];
});
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105