简体   繁体   中英

create an object array from a form in javascript

This is the kind of ptoblem that in python i take two minutes to solve but in js or jquery i fight for hours... i have a form and i need to elaborate the data client-side.

With :

var serializedData = $('form#ae_form_grid').serialize() 

i obtain this:

"id=13&quantita_gen_grid=2&prezzo_gen_grid=120&sconto_gen_grid=&prezzo-15=120&quantita-15=4&sconto-15=&selezionato-16=on&prezzo-16=120&quantita-16=2&sconto-16=&prezzo-14=120&quantita-14=2&sconto-14=&selezionato-17=on&prezzo-17=122&quantita-17=3&sconto-17="

i need to create an object array possibly with this from:

["16":{ prezzo:120,quantita:2,sconto:""},"17":{prezzo:122,quantita:3,sconto:""}]

16 and 17 are from the keys with "selezionato" in the name and prezzo, quantita... are the -16 and -17 ..

i tried with:

    $.each(serializedData.split('&'), function (index, elem) {
        var vals = elem.split('=');
        var selected = vals[0].split("-");
        if (selected[0] == "selezionato") {
            sel.push(selected[1])
        }
    })

and i have an array of the right key but i can go further.

thanks F

Here you are:

 var input = "id=13&quantita_gen_grid=2&prezzo_gen_grid=120&sconto_gen_grid=&prezzo-15=120&quantita-15=4&sconto-15=&selezionato-16=on&prezzo-16=120&quantita-16=2&sconto-16=&prezzo-14=120&quantita-14=2&sconto-14=&selezionato-17=on&prezzo-17=122&quantita-17=3&sconto-17="; //["16":{ prezzo:120,quantita:2,sconto:""},"17":{prezzo:122,quantita:3,sconto:""} var array = input.split('&'); var attributes = ['prezzo', 'quantita', 'sconto']; var keys = $.map(array, function(value) { var string = value.split('=')[0]; if (string.indexOf(attributes[0]) > -1) return string.split('-')[1]; }); keys = $.unique(keys).sort(); //console.log(JSON.stringify(keys)); var result = [] $.each(keys, function(index, key) { var item = {}; var obj = {}; $.each(array, function(i, v) { var k = v.split('=')[0]; //console.log("==" + k); if (k.indexOf(key) > -1) { //console.log("====" + k.split('-')[0]); if ($.inArray(k.split('-')[0], attributes) > -1) { obj[k.split('-')[0]] = v.split('=')[1]; //console.log(JSON.stringify(obj)); } } }); //console.log(JSON.stringify(obj)); item[key] = obj; result.push(item); }); $('span').text(JSON.stringify(result)); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <span></span> 

Hope this help.

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