I have several HTML elements in which I get the values using JQuery and array:
var trads = $("select[name='personal[]']").map(function(){return $(this).val();}).get();
var num_trad = trads.length;
var langs = new Array();
var values = new Array();
var approved = new Array();
for (var i=1; i<=num_trad; i++){
langs.push($("select[name='lang_"+i+"[]']").map(function(){return $(this).val();}).get());
values.push($("input[name='words_"+i+"[]'").map(function(){return $(this).val();}).get());
values.push($("input[name='approved_"+i+"[]'").map(function(){return $(this).val();}).get());
}
console.log(trads);
console.log(langs);
console.log(values);
.divs{float:left;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select name="personal[]">
<option value="1001">Mark</option>
<option value="1002">Rose</option>
</select>
<div style="clear:both;">
<div class="divs">
<select name="lang_1[]">
<option value="English">English</option>
<option value="Spanish">Spanish</option>
</select>
</div>
<div class="divs">
<input name="words_1[]" value="302">
<input name="approved_1[]" value="yes">
</div>
</div>
<div style="clear:both;">
<div class="divs">
<select name="lang_1[]">
<option value="English">English</option>
<option value="Spanish" selected>Spanish</option>
</select>
</div>
<div class="divs">
<input name="words_1[]" value="180">
<input name="approved_1[]" value="no">
</div>
</div>
<hr style="clear: both;">
<select name="personal[]">
<option value="1001">Mark</option>
<option value="1002" selected>Rose</option>
</select>
<div style="clear:both;">
<div class="divs">
<select name="lang_2[]">
<option value="English">English</option>
<option value="Spanish" selected>Spanish</option>
</select>
</div>
<div class="divs">
<input name="words_2[]" value="236">
<input name="approved_2[]" value="yes">
</div>
</div>
<hr style="clear: both;">
As the output is shown separately and I would like to sort these values as a JSON string getting something similar like this:
"1001":{ content:[{ language: "English", words: "302", approved: "yes" }, { language: "Spanish", words: "180", approved: "no" }] }, "1002":{ content:[{ language: "Spanish", words: "236", approved: "yes" }] }
How can I achieve it?
I will appreciate your help.
In order for the resulting json to be as you want, you can place the values in a chain concatenating them using string templates, you also need one
for
that goes through the personnel array and another that goes through the languages it has so that they are separated, taking care that they are defined:The code is working as follows:
And this is the result:
I hope it helps you, greetings.
I have included an additional routine for the output to be of type JSON in your code, I hope it can help you.
The arrays are unified to generate a JSON-like output like this: