'Get name and create a multidimensional array with jQuery
I have this
<input data-sector="10" name="people" value="21">
<input data-sector="10" name="people" value="22">
<input data-sector="11" name="people" value="23">
<input data-sector="11" name="people" value="24">
<input data-sector="12" name="people" value="25">
and with jQuery, I need transform to this:
var json = {"10":[21,22], "11":[23,24], "12":[25]}
I use this, but wont work. I need help.
var code = [];
$('[name=people]').each(function () {
var local = $(this);
code[local.data('sector')].push.local.val();
});
Solution 1:[1]
pushis a function, you have to call it with().codeshould be an object, not an array.- If the object property isn't already created, you have to create it with an empty array before you can push onto it.
var code = {};
$('[name=people]').each(function() {
var local = $(this);
var sector = local.data('sector');
if (!code[sector]) {
code[sector] = [];
}
code[sector].push(local.val());
});
console.log(code);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input data-sector="10" name="people" value="21">
<input data-sector="10" name="people" value="22">
<input data-sector="11" name="people" value="23">
<input data-sector="11" name="people" value="24">
<input data-sector="12" name="people" value="25">
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Barmar |
