0

I need to create dynamically hidden elements with name - value to store a JSON object.

For this input:

json_structure = {
    'var_1':'value_1',
    'var_2': {
        'var_2_1':'value_2_1',
        'var_2_2':'value_2_2'
    },
    'var_3': 'value_3'
};

should have

<input type="hidden" name="var_1" value="value_1" />
<input type="hidden" name="var_2[var_2_1]" value="value_2_1" />
<input type="hidden" name="var_2[var_2_2]" value="value_2_2" />
<input type="hidden" name="var_3" value="value_3" />

EDIT1 Here is my example, but works only for a one level object. For multiple levels need to make a recursive function to build the entire structure.

for(var key in json_structure ) {
        if(json_structure .hasOwnProperty(key)) {
            var hiddenField = document.createElement("input");
            hiddenField.setAttribute("type", "hidden");
            hiddenField.setAttribute("name", key);
            hiddenField.setAttribute("value", json_structure [key]);

            form.appendChild(hiddenField);
         }
    }

Is there a way to do this in a JavaScript or jQuery function which makes this easier?

Thank you in advance!

2
  • yes, i will add a short code to demonstrate Commented Dec 13, 2017 at 8:58
  • Please add what you have tried so far? Commented Dec 13, 2017 at 9:02

2 Answers 2

3

You can use some recursive approach to generate the input code where use Object.keys and Array#forEach method for iterating over the object properties.

var json_structure = {
  'var_1': 'value_1',
  'var_2': {
    'var_2_1': 'value_2_1',
    'var_2_2': 'value_2_2'
  },
  'var_3': 'value_3'
};

// function forr generating input
function genInput(obj, res, prefix) {
  // get all the object keys and iterate
  Object.keys(obj).forEach(function(k) {
    // generate the name with prefix
    var name = prefix ? prefix + '[' + k + ']' : k;

    // check property value is object
    // in case its object call the function recursively
    if (typeof obj[k] == 'object')
      // skip null by checking value is truthy
      obj[k] && genInput(obj[k], res, name);

    // else generate the input and push into the output array  
    else
      res.push('<input type="hidden" name="' + name + '" value="' + obj[k] + '"/>')
  })

  // finally return the array generated
  return res;
}

console.log(
  genInput(json_structure, [])
)


For generating DOM element and updating either you can use jQuery with the above code or with pure java do something like this.

var json_structure = {
  'var_1': 'value_1',
  'var_2': {
    'var_2_1': 'value_2_1',
    'var_2_2': 'value_2_2'
  },
  'var_3': 'value_3'
};

function genInput(obj, form, prefix) {
  Object.keys(obj).forEach(function(k) {
    var name = prefix ? prefix + '[' + k + ']' : k;
    if (typeof obj[k] == 'object') {
      obj[k] && genInput(obj[k], form, name);
    } else {
      var hiddenField = document.createElement("input");
      hiddenField.setAttribute("type", "hidden");
      hiddenField.setAttribute("name", name);
      hiddenField.setAttribute("value", obj[k]);
      form.appendChild(hiddenField);
    }
  })
}

genInput(json_structure, document.getElementsByTagName('form')[0])
<form></form>

With jQuery :

var json_structure = {
  'var_1': 'value_1',
  'var_2': {
    'var_2_1': 'value_2_1',
    'var_2_2': 'value_2_2'
  },
  'var_3': 'value_3'
};

// function forr generating input
function genInput(obj, res, prefix) {
  Object.keys(obj).forEach(function(k) {
    var name = prefix ? prefix + '[' + k + ']' : k;
    if (typeof obj[k] == 'object')
      obj[k] && genInput(obj[k], res, name);
    else
      res.push('<input type="hidden" name="' + name + '" value="' + obj[k] + '"/>')
  })
  return res;
}

// append the array of html string
$('form').append(genInput(json_structure, []))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form></form>

Sign up to request clarification or add additional context in comments.

7 Comments

Thank you for your code. This works OK for the provided example. An json object can also contains arrays as value instead strings or objects.
My intention is to find if already exist a function in javascript or jquery which cand do this. I see that my question is not concise.
@vasilenicusor : i think, there is no such predefined function
yah, I will make a full solution and I will come with the result. Thank you
I will accept your solution with a minor change : if (typeof obj[k] == 'object' && obj[k] != null) instead of if (typeof obj[k] == 'object')
|
1

You don't actually need jQuery in this case.

Here's a slightly different version.

var json_structure = {
    'var_1':'value_1',
    'var_2': {
        'var_2_1':'value_2_1',
        'var_2_2':'value_2_2'
    },
    'var_3': 'value_3'
};

function createHiddenInput(name, value) {
  var hiddenInput = document.createElement("input");
  hiddenInput.setAttribute("type", "hidden");
  hiddenInput.setAttribute("name", name);
  hiddenInput.setAttribute("value", value);
  document.body.appendChild(hiddenInput);
  console.log(hiddenInput);
}

function generateInputs(structure, prepend) {
  for (var propertyKey in structure) {
    if (structure.hasOwnProperty(propertyKey)) {
      var property = json_structure[propertyKey]
      if (typeof property === 'object') {
        generateInputs(property, propertyKey)
      } else {
        var name = prepend ? prepend + '[' + propertyKey + ']' : property;
        createHiddenInput(name, propertyKey)
      }
    }
  }
}

generateInputs(json_structure)
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
</head>
<body>
</body>
</html>

2 Comments

Nice, with Vanilla JS.
is same as previous answer

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.