简体   繁体   中英

javascript dynamically add values to array

I'm trying to loop over the checkboxes in a form and add their values to a multidimensional javascript object. The ' attrib ' data attribute will be the key. Possible key values are ' category ', ' product_group ' and ' language ' but I'd rather add them dynamically in case any more get added in the future.

I want to end up with an object like this, which I can easily send as a json_encode 'd single value to the server.

values = {
    'category' : {1,2,3},
    'product_group' : {4,5,6},
    'language': {'en','fr','de'}
};

Code below. Here obviously each iteration overwrites existing values instead of adding to it. I'm unsure where I can create values[key] as an object ... ?

$('.filter input, .multiselect-container input').change(function() {
    var values = {}
    $('.filter input:checked').each(function() {
        if($(this).is(':checked')) {
            var key = $(this).data('attrib')
            var value = $(this).val()
            values[key] = value
            // values[key].push(value) = calling method push of undefined ...
        }
        else {
            // Remove value
        }       
    })
    console.log(values) 
})

Your error is due to the fact that values[key] is undefined , therefore does not have a push method.

Try this code:

        if($(this).is(':checked')) {
            var key = $(this).data('attrib')
            var value = $(this).val()
            values[key] = values[key] || [] // initialize with empty array
            values[key].push(value)
        }

Not sure that's what you are looking for:

if(!values[key])
   values[key]=new Array();

values[key].push(value);

But this way you can add an array of value to every key.

Try this:

        if($(this).is(':checked')) {
            var key = $(this).data('attrib')
            var value = $(this).val()
            if(typeof values[key]  == "undefined")
            values[key] = [];
            values[key].push(value);

        }
        else {
            // Remove value
        }       

First, your data representation is not correct. The object attributes should be arrays like this:

values = {
    'category' : [1,2,3],
    'product_group' : [4,5,6],
    'language': ['en','fr','de']
};

With that data representation, this piece of code will do what you want:

$('.filter input, .multiselect-container input').change(function() {
var values = {}
$('.filter input:checked').each(function() {
    if($(this).is(':checked')) {
        var key = $(this).data('attrib')
        var value = $(this).val()
        values[key] = value
        if (values.key == undefined){
            //Check if key exists. If not, create it as an array
            values[key] = Array()
            values[key].push(value)
        }
        else{
            values[key].push(value)
        }
    }
    else {
        // Remove value
    }       
})
console.log(values) 

})

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