The first parameter to the callback in each
is the index in the array. You could compare this to the length of your array.
However, since you appear to be trying to build a json string, I would just build a javascript object and then JSON.stringify
it and save you the trouble.
Example:
var arr = [];
$j(".form-builder").each(function(){
arr.push({ type: $j(this).attr("type") });
});
var data_json = JSON.stringify(arr);
To demonstrate that this will produce the same result (save some white space which isn't significant) as manually building strings (and as an excuse to use the new snippet function):
$j = $;
// Built as an array of objects and then stringify
var arr = [];
$j(".form-builder").each(function(){
arr.push({ type: $j(this).attr("type") });
});
var data_json = JSON.stringify(arr);
alert("built as an array: " + data_json);
// Built with string concat
var items = $j(".form-builder");
var count = items.length;
data_json = "[";
items.each(function(i){
data_json+='{ "type":"'+$j(this).attr("type")+'"';
if (i<count -1) {
data_json+='},';
}
else {
data_json += '}';
}
});
data_json += "]";
alert("built with string concat: " + data_json);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-builder" type="foo"></div>
<div class="form-builder" type="bar"></div>
<div class="form-builder" type="la"></div>
<div class="form-builder" type="lala"></div>