简体   繁体   中英

Split Strings into Array of Objects

I have list of lat/lng stored in DB

If checkbox is checked I am getting the value in an array name='checkbox[]' .
Consider my HTML is:

<input type="checkbox" value="123,456" />
<input type="checkbox" value="789,1011" />

I'd like the resulting data in that form (array of objects)

[
    {lat: "123", lng: "456"},
    {lat: "789", lng: "1011"} 
]

I tried this one, but it does not split and store data in lat and lng

$(document).ready(function() {

  var tmp = [];

  $("input[name='checkbox[]']").change(function() {
    var checked = $(this).val();
    if ($(this).is(':checked')) {
      tmp.push(checked);
      const [lat1[], lon1[]] = tmp.split(',');
    } else {
      tmp.splice($.inArray(checked, tmp), 1);
    }
  });

  $('#show_all_point').on('click', function() {
    alert(lat1, lon1);
  });

});

Create a reusable getPoints() function which uses jQuery's Elements .filter() with the :checked selector:

 function getPoints() { return $(":checkbox").filter(":checked").get().reduce((a, el) => { const ll = el.value.split(","); a.push({lat:ll[0], lng:ll[1]}); return a; }, []); } $('#show_all').on('click', function () { const points = getPoints(); alert(JSON.stringify(points, null, 4)) });
 <input type="checkbox" value="123,456" /> <input type="checkbox" value="789,1011" /> <button id="show_all">SHOW SELECTED POINTS</button> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM