1

I am trying to populate my input fields based on the retrieved JSON object. The field names in my form would be something like:

  1. fullName
  2. account.enabled
  3. country.XXX.XXXX

The function should return something like below for the above fields

  1. aData["fullName"]
  2. aData["account"]["enabled"]
  3. aData["country"]["XXX"]["XXXX"]

How should I write my a function that returns a matching JSON entry for a given HTML field's name ?

abiieez
  • 3,139
  • 14
  • 57
  • 110
  • possible duplicate of [How do I enumerate the properties of a javascript object?](http://stackoverflow.com/questions/85992/how-do-i-enumerate-the-properties-of-a-javascript-object) – Quentin Sep 18 '13 at 16:42
  • 1
    It's not clear if you want to populate the HTML fields based on the names of the JSON entries to identify them, or if you want a function that returns a matching JSON entry for a given HTML field's name. – haylem Sep 18 '13 at 16:45
  • Sorry for not being clear. I have updated my question. – abiieez Sep 18 '13 at 16:51

2 Answers2

4

you could use the attached method that will recursively look for a given path in a JSON object and will fallback to default value (def) if there is no match.

var get = function (model, path, def) {
    path = path || '';
    model = model || {};
    def = typeof def === 'undefined' ? '' : def;
    var parts = path.split('.');
    if (parts.length > 1 && typeof model[parts[0]] === 'object') {
      return get(model[parts[0]], parts.splice(1).join('.'), def);
    } else {
      return model[parts[0]] || def;
    }
  } 

and you can call it like that :

get(aData, 'country.XXX.XXXX', ''); //traverse the json object to get the given key
Nicolas ABRIC
  • 4,925
  • 28
  • 18
1

Iterate over the form elements, grab their names, split on '.', then access the JSON Object?

Something like:

var getDataValueForField = function (fieldName, data) {
  var namespaces = fieldName.split('.');
  var value      = "";
  var step       = data;

  for (var i = 0; i < namespaces.length; i++) {
    if (data.hasOwnProperty(namespaces[i])) {
      step = step[namespaces[i]];
      value = step;
    } else {
      return (""); // safe value
    }
  }
  return (value);
};

var populateFormFields = function (formId, data) {
   var fields = document.querySelectorAll('#' + formId + ' input');

   for (var i = 0; i < fields.length; i++) {
     fields[i].value = getDataValueForField(fields[i].name, data);
   }
};

populateFormFields('myForm', fetchedFromSomeWhere());
haylem
  • 22,460
  • 3
  • 67
  • 96