Home > Mobile >  Creating an object array in foreach
Creating an object array in foreach

Time:02-10

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  name="l1" data-pos="a" data-side="left"/>
<input  name="l2" data-pos="b" data-side="left"/>
<input  name="l3" data-pos="c" data-side="left"/>

<input  name="r1" data-pos="a" data-side="right"/>
<input  name="r2" data-pos="b" data-side="right"/>
<input  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);

CodePudding user response:

You need to initialise a new object for info[side] before you can use info[side][pos]

info[side] = info[side] || {}

this is a common pattern to either use the existing value if there is one or create a new one object if needed.

You can then use this object directly without the need for the info variable which was getting re-used for different sets of values.

var sides = {};

$(".elm").each(function () {

  var pos   = $(this).data('pos').toUpperCase(); //a,b,c
  var side  = $(this).data('side'); //left, right
  var val   = $(this).val();

  sides[side] = sides[side] || {};
  sides[side][pos] = val;
});

var output = { name: "title1", data: [] };
output.data.push(sides);

console.log(JSON.stringify(output))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input  name="l1" data-pos="a" data-side="left" value="20"/>
<input  name="l2" data-pos="b" data-side="left" value="20"/>
<input  name="l3" data-pos="c" data-side="left" value="20"/>

<input  name="r1" data-pos="a" data-side="right" value="20"/>
<input  name="r2" data-pos="b" data-side="right" value="20"/>
<input  name="r3" data-pos="c" data-side="right" value="20"/>

  • Related