I'm trying to loop over input elements in div, to create an array of objects
<div id="time">
<input type="text" name="from" placeholder="12:00 AM" />
<input type="text" name="to" placeholder="12:30 AM" />
<input type="text" name="from" placeholder="13:00 AM" />
<input type="text" name="to" placeholder="13:30 AM" />
</div>
I'm trying to create the following array of objects.
unavailability: [
{ from: '12:00', to: '12:30' },
{ from: '13:00', to: '13:30' }
]
Here is what I have tried so far, but result is quite different.
var dataArray = []
$("#time").find('input').each(function() {
var data = {};
data[this.name] = this.value
dataArray.push(data);
});
console.log(dataArray)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="time">
<input type="text" name="from" placeholder="12:00 AM" />
<input type="text" name="to" placeholder="12:30 AM" />
<input type="text" name="from" placeholder="13:00 AM" />
<input type="text" name="to" placeholder="13:30 AM" />
</div>
JSFiddle
Creating an array of objects We can represent it as an array this way: let cars = [ { "color": "purple", "type": "minivan", "registration": new Date('2017-01-03'), "capacity": 7 }, { "color": "red", "type": "station wagon", "registration": new Date('2018-03-03'), "capacity": 5 }, { ... }, ... ]
If we want to loop through an array, we can use the length property to specify that the loop should continue until we reach the last element of our array.
Introduction to looping through objects using javascript If you have an array that is considered to be an object in javascript, you can't loop through the array using map(), forEach(), or a for..of loop.
You may iterate over all the elements having name attribute value as from
. To get the to
value, use next()
method of jQuery.
Use .val()
method to get the value of item.
$('#submit').click(function() {
var data = [];
$('#time input[name="from"]').each(function() {
data.push({
from: $(this).val(),
to: $(this).next().val()
});
});
console.log(data);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Enter times in the below textboxes
<div id="time">
<input type="text" name="from" placeholder="12:00 AM" />
<input type="text" name="to" placeholder="12:30 AM" />
<input type="text" name="from" placeholder="13:00 AM" />
<input type="text" name="to" placeholder="13:30 AM" />
</div>
<button id="submit">Submit</button>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With