[英]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[]'
.如果选中复选框,我将在数组
name='checkbox[]'
获取值。
Consider my HTML is:考虑我的 HTML 是:
<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
我试过这个,但它不会在
lat
和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:创建一个可重用的
getPoints()
函数,它使用 jQuery 的 Elements .filter()
和:checked
选择器:
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.