I have a dynamic elements and I need to fetch all adults first name and last name into an array of objects using jquery
like
[
[
{
"first_name": "Anish",
"last_name": "gopi"
}, {
"first_name": "Vinay",
"last_name": "prasad"
}
],
[
{
"first_name": "Ananaya",
"last_name": "vital"
}, {
"first_name": "Guru",
"last_name": "govind"
}
]
]
let i = 0;
$('.pax_details').each(function(index, item) {
$(item).find('.adult_pax').each(function(index, adult) {
console.log($(adult).find('input[name^="first_name_"]').val());
});
i++;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div class="pax_details">
<div class="adult_pax">
<input name="first_name_1" value="Anish" />
<input name="last_name_1" value="gopi" />
</div>
<div class="adult_pax">
<input name="first_name_2" value="Vinay" />
<input name="last_name_2" value="prasad" />
</div>
</div>
<div class="pax_details">
<div class="adult_pax">
<input name="first_name_3" value="Ananaya" />
<input name="last_name_3" value="vital" />
</div>
<div class="adult_pax">
<input name="first_name_4" value="Guru" />
<input name="last_name_4" value="govind" />
</div>
</div>
3
Answers
This solution does what you want:
It first scans for the
.pax_details
elements, then subsequently looks for all<input>
elements within them.To get what you ask (nested array), you indeed need to loop the pax_details
jQuery
Plain JS
The jQuery-way to do this would be to map all the details to an array of adults, where each adult is a reduction of the fields.
You can grab the input field’s
name
and use a regular expression to match on everything before the trailing underscore + number.The trick here is to wrap the returned values in an square brackets. If you do not, you will get a flat list at the end.