The Issue
I am trying to convert form inputs to a json object but having difficulty trying to achieve this, below is a snippet of the HTML which I have and the JSON which I'm trying to get.
{
"2019-01-23": [
{
id: 1,
period: 'am'
},
{
id: 2,
period: 'pm'
}
]
}
<select name="dates[2019-01-23][0][id]">
<option value="1" selected>1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select name="dates[2019-01-23][0][period]">
<option selected>am</option>
<option>pm</option>
</select>
<select name="dates[2019-01-23][1][id]">
<option value="1">1</option>
<option value="2" selected>2</option>
<option value="3">3</option>
</select>
<select name="dates[2019-01-23][1][period]">
<option>am</option>
<option selected>pm</option>
</select>
What I've tried
var inputs = $(':input').serializeArray();
var json = [];
$.each(inputs, function(key, input) {
var names = input.name.split(/\[(.*?)\]/);
var data = [];
data[names[1]] = [];
data[names[1]][names[3]] = { id: null, period: null };
if(names[5] == 'id') {
data[names[1]][names[3]].id = input.value;
}
if(names[5] == 'period') {
data[names[1]][names[3]].period = input.value;
}
json.push(data);
});
But this doesn't quite achieve what I'm after (multiple of the same date) and I'm getting a bit lost now, I'm sure there must be a way of doing this a lot easier.