Home > Mobile >  Jquery array get item x to item y
Jquery array get item x to item y

Time:04-21

I'm struggeling to iterate over an array in a certain way. I've read numerous posts here but just can't get it to work.

I have an array called art_stuff like this:

[
  {
    "block": 0,
    "amt": 5
  },
  {
    "block": 1,
    "amt": 1
  },
  {
    "block": 2,
    "amt": 2
  },
  {
    "block": 3,
    "amt": 3
  },
  {
    "block": 4,
    "amt": 4
  }
]

And a JSON response like this:

"products":[{
  "id":1, //0
  "id":2, //1 
  "id":3, //2 
  "id":4, //3 
  "id":5, //4 
  "id":6, //5 
  "id":7, //6
   etc ....

In the $.each I first loop over the array. The amt in the array is the amount of id's I need from the JSON response. So for example:

  • Block 0 needs 5 id's from the JSON response. So that's index 0 - 4 (= id 1 to id 5)
  • Block 1 needs 1 id, start at where block 0 stopped, so that's index 5 (= id 6)
  • Block 2 needs 2 id's, start at where block 1 stopped, so that's index 6 - 7 (= id 7 and id 8) etc....

So basically each each block starts looping at where the previous block stopped.

So for example:

$.getJSON(url-to-json, function(data) {
  ........

  var start_count = 0 
  var end_count = 0

  $.each(art_stuff, function(index, art_block){

   start_count = start_count   art_block.amt 
   end_count = start_count   1

   console.log('block_'   art_block.block   ' starts at: '   start_count   ', and ends at: '   end_count)

  //var prods = data.products.slice(start_count, end_count)

Expected result would be:

block_0 starts at: 0, and ends at: 4
block_1 starts at: 5, and ends at: 5
block_2 starts at: 6, and ends at: 7
block_3 starts at: 8, and ends at: 10
etc...

I don't understand how to create a proper start and end point to slice the JSON response.

Any help greatly appreciated!

CodePudding user response:

You can change these two lines:

   start_count = start_count   art_block.amt 
   end_count = start_count   1

to

   end_count = start_count   art_block.amt - 1

then at the end of your $.each add

   start_count = end_count   1;

Together, giving:

var art_stuff = [{
    "block": 0,
    "amt": 5
  },
  {
    "block": 1,
    "amt": 1
  },
  {
    "block": 2,
    "amt": 2
  },
  {
    "block": 3,
    "amt": 3
  },
  {
    "block": 4,
    "amt": 4
  }
]
var start_count = 0
var end_count = 0

$.each(art_stuff, function(index, art_block) {

  end_count = start_count   art_block.amt - 1;

  console.log('block_'   art_block.block   ' starts at: '   start_count   ', and ends at: '   end_count)

  //... other code

  start_count = end_count   1; // ready for next iteration

}); // end of $.each
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

  • Related