I am adding data to a form from objects that can be multi layered.
Form Example
<form id="myForm">
<input name="foo" />
<input name="bar" />
</form>
Data Example
var myData = {
level1: {
foo: 'hello',
level2: {
bar: 'greetings'
}
}
}
Add data to form
$.each(data, function (i, e) {
var field = $('[name="' + i + '"]');
if (field.is('input')) field.val(e);
});
Now obviously this won't work, so I have two options.
A) Flatten the object
var myResult = {
level1 : '',
foo : 'hello',
level2 : '',
bar : 'greetings'
}
B) Recursively go through the object
But I think to even do A, I need to do B anyway. So B is the faster choice. Now, how do I recursively go through an object? I have been working on this fiddle and tried to implement a recursive for loop, but that loop does not extract the value from the object property. I am pretty spoiled by using jq $.each, but I don't know if it will work in this case.
http://jsfiddle.net/6d7L9qpw/1/
Here is a iterator function to get that key value:
var myData = {
level1: {
foo: 'hello',
level2: {
bar: 'greetings'
}
}
}
function recIterator(object, inputKey) {
for(var key in object) {
if(typeof object[key] == "object") {
return recIterator(object[key], inputKey);
} else {
if(key==inputKey) {
return object[key];
}
}
}
}
$(function() {
$("input[type=text]").each(function(ele) {
var key = $(this).attr("name");
$(this).val(recIterator(myData, key));
});
});
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.js"></script>
<form id="myForm">
<input name="foo" type="text" />
<input name="bar" type="text" />
</form>
Hope you can carry on from here :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With