Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript lodash range on array of JSON objects not returning

So on the lodash docs this is how I understand range, _.range(start, end).

So if I used .range() on an array of JSON objects. Like...

const arr = [
  {
    name: 'name',
  },
];

Lets say I had 20 objects and I did arr._.range(5, 5); I'd get back the 5th JSON object and 5 from there.

So I've created a map function that gives me back a list of JSON objects and I then use range on them, here's what I have:

import R from 'lodash';
const getJsonData = (offset, limit) => (
  R.map([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], x => ({
    title: `title ${x}`,
    subtitle: 'description',
    image_url: 'http://some-img-url.com',
    date: 'date',
    tag: 'tag',
    places: [
      {
        places: 'places',
      },
    ],
  }), R.range(offset, (limit + offset)))
);

So I'd call this like getJsonData(5, 5); but it still gives me back the full list of 20 JSON objects.

Am I misunderstanding how range works?

like image 939
pourmesomecode Avatar asked Sep 04 '26 04:09

pourmesomecode


1 Answers

The result you have is correct.

The map function from lodash does not accept a third parameter.

So the range call is not taken in account.

https://lodash.com/docs/4.17.4#map

So, I suggest you to use slice function like this:

import R from 'lodash';
const getJsonData = (offset, limit) => (
    R.slice(
        R.map([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], x => ({
            title: `title ${x}`,
            subtitle: 'description',
            image_url: 'http://some-img-url.com',
            date: 'date',
            tag: 'tag',
            places: [
                {
                    places: 'places',
                },
            ],
        }))
    , offset, limit + offset)
);
like image 95
ADreNaLiNe-DJ Avatar answered Sep 05 '26 18:09

ADreNaLiNe-DJ