2017-06-15 32 views
2

因此,在lodash文檔這是我如何理解範圍,_.range(start, end)Javascript lodash範圍的數組JSON對象不返回

所以,如果我在一個JSON對象數組上使用.range()。像...

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

可以說,我有20個對象,我做arr._.range(5, 5);我會從那裏拿回5 JSON對象和5。

所以我創建了一個地圖功能,讓我回JSON對象的列表,然後我用他們range,這裏就是我有:

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))) 
); 

所以我把這種喜歡getJsonData(5, 5);但它仍然給我回20個JSON對象的完整列表。

我誤解range的工作原理嗎?

+0

[有作爲 「JSON對象」 沒有這樣的事(http://benalman.com/news/ 2010/03/theres-no-such-thing-as-a-json /) – Andreas

+0

@Andreas對不起,只是我的措辭不好。但一般jist是'.range()'不工作的問題,我不理解爲什麼 – PourMeSomeCode

回答

1

您的結果是正確的。

來自lodashmap函數不接受第三個參數。

因此range電話沒有考慮在內。

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

所以,我建議你使用slice功能如下:

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) 
); 
+0

啊我沒關係。所以我真的需要做的。完全返回完整數組,然後調用'.range'。我會給出一個嘗試:) – PourMeSomeCode

+0

你可以'切片'整個陣列。我添加了一個例子。 –

+0

真棒歡呼的夥計!是的,我是一個白癡:)我會接受你的答案。有一件事,'offset,limit + offset'在'slice'之外。所以更新將是'))),偏移量,限制+偏移量,),);' – PourMeSomeCode