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 ?

3
  • possible duplicate of How do I enumerate the properties of a javascript object? Commented Sep 18, 2013 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. Commented Sep 18, 2013 at 16:45
  • Sorry for not being clear. I have updated my question. Commented Sep 18, 2013 at 16:51

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

1 Comment

this looks promising, I am giving it a try now. Thanks.
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());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.