I'm a beginner with JavaScript and query. I have an html form where the user can add or remove a group of fields. The group of fields contains 1 select and 3 inputs. The group of fields added have the same name of the previouses and so on. What I'm trying to do is retrieve the value creating a structure like this.
{
"colture1": [{
"code_app": "A2",
"long": "1",
"lat": "103"
}, {
"code_app": "B34",
"long": "11",
"lat": "12"
}],
"colture2": [{
"code_app": "GH3456",
"long": "55",
"lat": "90"
}]
// ....and so on
}
If the user selects a colture that already exist in the object, I'd like to add the others value in the same key as you can see in "colture1". My problem is here, I can't create an array where I can add the others value, now my function override the preovious values, It writes the last one values and it doesn't create an array.
This is my function
$('#create_json').on("click", function(e) {
const json_data = {};
var cat = "";
for (const input of document.querySelectorAll(".card[mainBlock] select, .card[mainBlock] input")) {
if (input.tagName === 'SELECT') {
cat = input.value;
} else {
(json_data[cat] = json_data[cat] || {})[input.name] = input.value;
}
}
console.log(JSON.stringify(json_data));
})
Here I can put a demo here https://jsfiddle.net/ou7h4f2m/3/. Thank you in advance