jquery - Combining values of javascript objects -
hy guys, have form multiple inputs , dropdowns , depending on user selection final result this:
var optionvariants = [ { attribute: { id: 1, name: 'color' }, values: ['red', 'green'] }, { attribute: { id: 2, name: 'size' }, values: ['small', 'medium', 'large'] } ];
all want loop trough object , make new object this:
var newobject = [ { attributes: [ { id: 1, name: 'color', value: 'red' }, { id: 2, name: 'size', value: 'small' } ] }, { attributes: [ { id: 1, name: 'color', value: 'red' }, { id: 2, name: 'size', value: 'medium' } ] }, { attributes: [ { id: 1, name: 'color', value: 'red' }, { id: 2, name: 'size', value: 'large' } ] }, { attributes: [ { id: 1, name: 'color', value: 'green' }, { id: 2, name: 'size', value: 'small' } ] }, { attributes: [ { id: 1, name: 'color', value: 'green' }, { id: 2, name: 'size', value: 'medium' } ] }, { attributes: [ { id: 1, name: 'color', value: 'green' }, { id: 2, name: 'size', value: 'large' } ] } ];
i have tried create empty arrays, push items in them, loop trough them cannot find correct solution group them want.
i'm not javascript expert , i'm still learning gentle me :d
this have tried:
var option_groups = [ ["red", "green", "blue"], ["s", "m", "l"], ["cotton", "silk"] ]; var variants = []; var combos = []; var nnew = []; var variant = []; var option = ""; var ttmp = [] var combo = []; if (option_groups.length > 1) { (var in option_groups[0]) { variants.push([option_groups[0][i]]); } (var = 1; < option_groups.length; i++) { combos = []; (var j in variants) { variant = variants[j]; nnew = []; (var x in option_groups[i]) { option = option_groups[i][x]; ttmp = []; (var d in variant) { ttmp.push(variant[d]); } ttmp.push(option); nnew.push(ttmp); } combos.push(nnew); } variants = []; (var y in combos) { combo = combos[y]; (var z in combo) { variants.push(combo[z]); } } } console.log(variants); }
var optionvariants = [ { attribute: { id: 1, name: 'color' }, values: ['red', 'green'] }, { attribute: { id: 2, name: 'size' }, values: ['small', 'medium', 'large'] } ]; var firstobjectvalues = optionvariants[0]['values']; var secondobjectvalues = optionvariants[1]['values']; var firstobjectvaluesamount = firstobjectvalues.length; var secondobjectvaluesamount = secondobjectvalues.length; var newobject = []; (var = 0; < firstobjectvaluesamount; i++) { (var j = 0; j < secondobjectvaluesamount; j++) { var obj1 = {}; obj1.id = optionvariants[0]['attribute'].id; obj1.name = optionvariants[0]['attribute'].name; obj1.value = optionvariants[0]['values'][i]; var obj2 = {}; obj2.id = optionvariants[1]['attribute'].id; obj2.name = optionvariants[1]['attribute'].name; obj2.value = optionvariants[1]['values'][j]; var finalobj = { attributes: [obj1, obj2] }; newobject.push(finalobj); } } console.log(newobject);
that's it!
Comments
Post a Comment