Ad

Get Name And Create A Multidimensional Array With JQuery

- 1 answer

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();
});
Ad

Answer

  1. push is a function, you have to call it with ().
  2. code should be an object, not an array.
  3. 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">

Ad
source: stackoverflow.com
Ad