I have an array of objects and would like to insert their values into a set of inputs. I thought that using jQuery's val() to mass assign these values within a few for-loops but it only returns the very last value of the two objects. What am I doing wrong? Better yet, is there a better way to do this without having to loop 3 times?
$(function() {
var arr = [{v1: 1, v2: 2, v3: 3, v4: 4}, {v1: 5, v2: 6, v3: 7, v4: 8}];
for (var i = 0; i < arr.length; i++) {
for (key in arr[i]) {
$('input').val(function(index) {
return arr[i][key]
});
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="text" />
<input type="text" />
<input type="text" />
<input type="text" />
</div>
<div>
<input type="text" />
<input type="text" />
<input type="text" />
<input type="text" />
</div>
arrcannot be changed?