I have a JSON object as {a: 1, b: 2, c: [4, 5, 6], d: {x: 7, y: 8, z: [9, 0]}}, how do I convert it to a form of elements?
I want to convert to this:
<input type="hidden" name="obj[a]" value="1"/>
<input type="hidden" name="obj[b]" value="2"/>
<input type="hidden" name="obj[c][]" value="4"/>
<input type="hidden" name="obj[c][]" value="5"/>
<input type="hidden" name="obj[c][]" value="6"/>
<input type="hidden" name="obj[d][x]" value="7"/>
<input type="hidden" name="obj[d][y]" value="8"/>
<input type="hidden" name="obj[d][z][]" value="9"/>
<input type="hidden" name="obj[d][z][]" value="0"/>
Any ideas?
These should do it:
with jQuery
JSFIDDLE DEMO
FYI, you can find a compatibility patch for
Array.isArrayat MDN.Or you can use
jQuery.isArray()instead.jQuery reworked
You may prefer this a bit. It doesn’t create an element, then clone it in the Array loop, but rather uses a little redundant code to create the elements.
JSFIDDLE DEMO
with native DOM API
If you’re having any performance issues, use the native API, and cache the DOM selection.
JSFIDDLE DEMO
Doesn’t require much more code, should work in all typically supported browsers, and should be very fast.
native API reworked to shorten
JSFIDDLE DEMO