简体   繁体   中英

Given lodash map, how to limit the # of results or slice?

I have the following:

import itemsMap from '../libs/items-map';
const _ = require('lodash');
const options = {};

_.map(itemsMap, (item, key) => {
  options[key] = key;
});

I then output in React like so:

  {
    _.map(itemsMap, (item, key) => (
        {key}
      />
    ))
  }

This currently outputs the entire items list,, I would like to output only 5.. I tired using slice like so:

  {
    _.map(itemsMap.slice(2), (item, key) => (
        {key}
      />
    ))
  }

This results in a TypeError: .default.slice is not a function

How can I limit the results?

Whatever loader/bundler is resolving your import isn't exposing itemsMap as an array. You may need to use require syntax like the 2 lines below that.

Also, since the key in your return statement is wrapped in curly brackets but no jsx tags, it's parsed as an object and doesn't render anything. see what happens on this codepen when you remove the <span> around {key} .

To your original question, the idiomatic way to limit items in lodash would be to use lodash.take like so:

_.map(_.take(itemsMap, 2), (item, key) => ( … ))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM