Home Loop over nested array and render divs with values
Reply: 6

Loop over nested array and render divs with values

AKr
1#
AKr Published in 2018-01-11 08:27:23Z

I have an array which looks somewhat like this:

arr = [
  ["10", "1", "1200", "630"],
  ["272", "45", "654", "654"],
  ["10", "139", "367", "372"],
  ["825", "134", "369", "371"]
];

The values inside of each array are params (x, y, width, height) for a div I want to render. So e.g. the first div should have the props:

left: 10,
top: 1,
width: 1200,
height: 630

My current implementation looks like this:

for (var i = 0; i < arr.length; i++) {
      $('<div/>', {
          class: 'class-' + i
        }).appendTo($('body'));
      for (var j = 0; j < arr[i].length; j++) {
            $('.class-' + i).css({
                position: 'absolute',
                left: arr[i][j],
                top: arr[i][j],
                width: arr[i][j],
                height: arr[i][j]
         });
     }
}

So in this case I would like to create 4 different divs for each array with the proper CSS styles given in each array. Unfortunately it is not working, because I face some issues with indexing.

Do you have an idea how to solve this?

Thanks!

Mihai Alexandru-Ionut
2#
Mihai Alexandru-Ionut Reply to 2018-01-11 08:46:16Z

The problem is with this part of code:

for (var j = 0; j < arr[i].length; j++) {
        $('.class-' + i).css({
            position: 'absolute',
            left: arr[i][j],
            top: arr[i][j],
            width: arr[i][j],
            height: arr[i][j]
        });
}

You have to set style of a given div only once. In your code it is setting css style for 4 times for every div which has class-i, where i= 1 to arr.length.

arr = [
       ["10px", "1px", "12", "63"],
       ["272px", "45px", "65", "65"],
       ["101px", "139px", "36", "37"],
       ["825px", "134px", "36", "31"]
     ];
for (var i = 0; i < arr.length; i++) {
        $('<div/>', {
            class: 'class-' + i
        }).appendTo($('body'));
        $('.class-' + i).css({
                position: 'absolute',
                left: arr[i][0],
                top: arr[i][1],
                width: arr[i][2],
                height: arr[i][3]
        });
}
div{
  background-color:red;
  border:1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

ItsGreg
3#
ItsGreg Reply to 2018-01-11 08:34:00Z

You don't want to iterate a second time though it. In your first for loop, you get ["10", "1", "1200", "630"]. If you loop through it again, you get a single value. Here's what you're looking for - I'm a bit rusty with jQuery, you could probably optimize that.

for (var i = 0; i < arr.length; i++) {
    var parent =  $('<div/>', {
        class: 'class-' + i
    }).appendTo($('body'));
    $('.class-' + i).css({
        position: 'absolute',
        left: arr[i][0],
        top: arr[i][1],
        width: arr[i][2],
        height: arr[i][3]
    });
}
magreenberg
4#
magreenberg Reply to 2018-01-11 08:34:48Z

for (var i = 0; i < arr.length; i++) {
  $('<div/>', {
    class: 'class-' + i
  }).appendTo($('body'));
  $('.class-' + i).css({
    position: 'absolute',
    left: arr[i][0],
    top: arr[i][1],
    width: arr[i][2],
    height: arr[i][3]
  });

}

You only need one loop.

guest271314
5#
guest271314 Reply to 2018-01-11 08:50:32Z

You can use .map(), pass an object to .css(). Note also, left and top values should have "px" concatenated to the numeric value

arr = [
  ["10px", "1px", "1200", "630"],
  ["272px", "45px", "654", "654"],
  ["10px", "139px", "367", "372"],
  ["825px", "134px", "369", "371"]
];
$("body")
  .append(
    arr.map(([left, top, width, height], i) =>
      $("<div>", {
        "class": "class-" + i,
        text: i,
        css: {left, top, width, height}
      }))
  );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>

plnkr http://plnkr.co/edit/4DgX13CoQAy9QC8oUA1T?p=preview

Deepansh Sachdeva
6#
Deepansh Sachdeva Reply to 2018-01-11 08:48:34Z

Here's a fiddle for you. Hope that helps.

var arr = [
       ["10", "1", "1200", "630"],
       ["272", "45", "654", "654"],
       ["10", "139", "367", "372"],
       ["825", "134", "369", "371"]
     ];
     
 arr.forEach(function(a) {
 	var div = $('<div/>').css({
    left: a[0],
    top: a[1],
    width:a[2],
    height: a[3]
  });
 	$('body').append(div);
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

HMR
7#
HMR Reply to 2018-01-12 12:13:02Z

Here is an example using reduce and recursive function:

var arr = [
  ["10px", "1px", "1200", "630"],
  ["272px", "45px", "654", "654"],
  ["10px", "139px", "367", "372"],
  ["825px", "134px", "369", "371"]
];
var mapValuesToCss = ([left, top, width, height])=>
  Object.assign(
    {left,top}
    ,{
      width:width+"px",
      height:height+"px"
    }
  );
var addIndexAsContent = (value,index)=>value.html(index)
var createDivsReduce = css =>
  css.reduce(
    (divs,css)=>
      divs.concat(
        $(
          "<div>",
          css
        )
      )
    ,[]
  );
var createDivsRecursive = divs => css => {
  if(css.length===0){
    return divs;
  }
  return createDivsRecursive
    (divs.concat($("<div>",css[0])))
    (css.slice(1));//recursively call itself
}
//using reduce
$("body")
  .append(
    createDivsReduce(arr.map(mapValuesToCss))
    .map(addIndexAsContent)
  );
//recursively
$("body")
  .append(
    createDivsRecursive([])(arr.map(mapValuesToCss))
    .map(addIndexAsContent)
  );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.310923 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO