i am struggeling to create an object array from two input-groups, each group has 3 inputs with data-side = left/right each input has class "elm" and data-pos = a/b/c
<input class="elm-left elm" name="l1" data-pos="a" data-side="left"/>
<input class="elm-left elm" name="l2" data-pos="b" data-side="left"/>
<input class="elm-left elm" name="l3" data-pos="c" data-side="left"/>
<input class="elm-right elm" name="r1" data-pos="a" data-side="right"/>
<input class="elm-right elm" name="r2" data-pos="b" data-side="right"/>
<input class="elm-right elm" name="r3" data-pos="c" data-side="right"/>
desired output is:
[
{
"name":"title1",
"data":[
{
"left" :{"A":10,"B":10,"C":10},
"right":{"A":20,"B":20,"C":20}
}
]
}
]
my output is:
...,"data":[
{
"left":{"A":20,"B":20,"C":20},
"right":{"A":20,"B":20,"C":20}
}
]
var sides = {};
var info = {};
$(".elm").each(function () {
var pos = $(this).data('pos').toUpperCase(); //a,b,c
var side = $(this).data('side'); //left, right
var val = $(this).val();
info[[pos]] = val;
sides[side] = info;
});
data.push(sides);
infoset for both sides, with values inserted to it regardless of their "side". In addition, you are assiginingsides[side] = infobutinfois an object so it is not cloned. At the end of the execution,sides['left']andsides['right']both refer to the exact same object.info[side] = { [pos] : val }withdata.push(info);looks better but leads to"data":[{"left":{"H":"10"},"right":{"H":"20"}}]info[side] =overwrites existing values, you needinfo[side][pos] =after initializing both side objects. I don't know where the "H" came from, if you are trying a new approach then add it fully inside the question.info[side]withinfo[side][pos]an error is thrown:info[side] is undefinedinfo[side] = info[side] || {}