javascript - Save data values from an input into an multidimensional array -


var dataarray = []; dataarray.push({ items: [] }); var items = $('#services_hidden').val(); var itemsarray = items.split(","); console.log("itemsarray: " + itemsarray); $.each( itemsarray, function( index, value ){     dataarray[0].items.push(value); }); console.log("dataarray " + json.stringify(dataarray)); 

this way want save data in array reading input value this:

<input id="services_hidden" value="item1,value1,item2,value2,item3,value3" /> 

so there can multiple items assigned specific value. @ moment looks wrong because it's saved items not seperated each other:

dataarray [{"items":["item1","value1","item2,"value2"]}] 

but want (i hope show correctly):

dataarray [{"items":{"item1:value1"},{"item2:value2"}}] 

so parent items , every 2 values in #services_hidden.val() seperated comma should create key:value pair.

what have change in code achieve this?

you can use reduce() do this

//select element id , value  var val = document.getelementbyid('services_hidden').value;  //split value @ , , create array  var ar = val.split(',');    //use reduce return result in data_array variable  var data_array = ar.reduce(function(r, e, i) {    //if index of element odd number, add result, element of array previous index number , current element    if (i % 2) r[0].items = (r[0].items || []).concat({      [ar[i - 1]]: e    });    //return result array.    return r;  }, [{}]);    //add result html  document.body.innerhtml += '<pre>' + json.stringify(data_array) + '</pre>';
<input id="services_hidden" value="item1,value1,item2,value2,item3,value3" />


Comments

Popular posts from this blog

javascript - Slick Slider width recalculation -

jsf - PrimeFaces Datatable - What is f:facet actually doing? -

angular2 services - Angular 2 RC 4 Http post not firing -