Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add nested object data to a form

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/

like image 960
tdoakiiii Avatar asked Feb 25 '26 21:02

tdoakiiii


1 Answers

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 :)

like image 72
mohamedrias Avatar answered Feb 27 '26 12:02

mohamedrias



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!