简体   繁体   中英

Remove array from javascript object

Context

I'm trying to implement a feature so that when the user clicks on a checkbox within a table, the attribute value and data-title of the checkbox should be stored in a JS object literal named selected as a new key-value pair array element.

In case the user clicks a second time on the same checkbox, the corresponding array element should be removed.

Issue

The first time a checkbox is clicked, an array is created in object selected as intended.

However, when the same checkbox is clicked a second time, instead of removing the corresponding array, a new one (repeated) is added .

Code

var selected = {items:[]};     
$('#table').on('click', 'input[type="checkbox"]', function() {
    var found = false;
    $.each(selected.items, function(i, val) {
        if (val.key == $(this).attr("value")) {
            selected.items.splice(i ,1);
            found = true;
            return false; //step out of each()
        }
    });

    if (found == false) {
        selected.items.push({key: $(this).attr("value"), value: $(this).attr("data-title")});
    }

    console.log(selected);
});

You have the wrong context of this inside each . it is no longer the element in the click handler

Try

$('#table').on('click', 'input[type="checkbox"]', function() {
    var found = false;
    var value = $(this).val();// store value from `this` before entering `each`
    $.each(selected.items, function(i, val) {
        if (val.key == value) {
            selected.items.splice(i ,1);
            found = true;
            return false; //step out of each()
        }
    });
    ....

First, I would recommend to use a key-value-pair object, as it is way easier for lookups.

var selected = { items : {} };

this way you would access your selected items using

selected.items[my.key]

maybe somethink like this...

var selected = {items:{}};     
$('#table').on('change', 'input[type="checkbox"]', function() {
    var checked = $(this).is(":checked"),
        title = $(this).data("data-title"),
        value = $(this).val();

    if (checked && !selected.items[value])
        selected.items[value] = title;
    else if (!checked && !!selected.items[value])
        delete selected.items[value];
});

how about this one:

var selected = { items:[] };

$('#table').on('click', 'input[type="checkbox"]', function() {
    selected.items = $('#table input[type="checkbox"]:checked').map(function(){
        return {
            key: $(this).attr('value'),
            value: $(this).attr('data-title')
        }
    }).toArray()
});

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