Reputation: 1853
I am trying an array in JavaScript with the following format by querying the DOM via JQuery:
[
{
"start": moment("10/03/2017","DD/MM/YYYY"),
"end": moment("18/03/2017", "DD/MM/YYYY")
},
{
"start": moment("01/04/2017","DD/MM/YYYY"),
"end": moment("05/04/2017", "DD/MM/YYYY")
},
{
"start": moment("11/04/2017","DD/MM/YYYY"),
"end": moment("15/04/2017", "DD/MM/YYYY")
}
]
I tried to create a JavaScript Object
in JQueries each()
function to do this but it is not working:
var avail_fruits = Array();
$(".avails").each(function(i, objer) {
//test
var ndate_group = $(objer).val().split(",");
var obj_date = new Object();
obj_date.start = moment(ndate_group[0],"DD/MM/YYYY");
obj_date.end = moment(ndate_group[0],"DD/MM/YYYY");
console.log(obj_date);
avail_fruits.push(obj_date);
});
Upvotes: 2
Views: 460
Reputation: 30360
If I understand your question correctly, you can achieve what is required by extracting the start
and end
dates as strings from each <input/>
element with jQuery like this:
const [start, end] = $(this).val().split(',');
You can then parse those strings via moment's utc()
method as shown below:
/* Declare results array */
const avail_fruits = [];
/* Iterate each input with avails class*/
$('.avails').each(function() {
/* Extract start,end date string from input value */
const [start, end] = $(this).val().split(',');
/* Parse start,end date strings with moment. Use utc()
to avoid timezone conversion */
avail_fruits.push({
start : moment.utc(start, 'DD/MM/YYYY'),
end : moment.utc(end, 'DD/MM/YYYY')
});
});
console.log(avail_fruits)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<input type="hidden" name="avail" class="avails" value="10/03/2017,18/03/2017">
<input type="hidden" name="avail" class="avails" value="01/04/2017,05/04/2017">
<input type="hidden" name="avail" class="avails" value="11/04/2017,15/04/2017">
Upvotes: 1