Javascript 是否可以只映射数组的一部分?(Array.map())

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39455224/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:34:44  来源:igfitidea点击:

Is it possible to map only a portion of an array? (Array.map())

javascriptarraysjsonreactjs

提问by connected_user

I am building a project using React.js as a front-end framework. On one particular page I am displaying a full data set to the user. I have an Array which contains this full data set. It is an array of JSON objects. In terms of presenting this data to the user, I currently have it displaying the whole data set by returning each item of data using Array.map().

我正在使用 React.js 作为前端框架构建一个项目。在一个特定页面上,我向用户显示了完整的数据集。我有一个包含这个完整数据集的数组。它是一个 JSON 对象数组。在向用户呈现这些数据方面,我目前通过使用 Array.map() 返回每个数据项来显示整个数据集。

This is a step in the right direction, but now I need to display only a portion of the data-set, not the whole thing, I also want some control in terms of knowing how much of the total data set has been displayed, and how much of the data set is yet to be displayed. Basically I am building something like a "view more" button that loads more items of data to the user.

这是朝着正确方向迈出的一步,但是现在我只需要显示数据集的一部分,而不是整个数据集,我还希望在知道显示了多少总数据集方面进行了一些控制,并且有多少数据集尚未显示。基本上,我正在构建类似“查看更多”按钮的东西,可以向用户加载更多数据项。

Here is what I am using now where 'feed' represents my Array of JSON objects. (this displays the whole data set.)

这是我现在使用的,其中 'feed' 代表我的 JSON 对象数组。(这将显示整个数据集。)

 return (
  <div className={feedClass}>
  {
    feed.map((item, index) => {
      return <FeedItem key={index} data={item}/>
    })
  }
  </div>
);

I am wondering if it is possible to use .map() on only a portion of the array without having to break up the array before hand? I know that a possible solution would be to hold the full data set, and break it off into portions, and then .map() those portions, but is there a way to .map() a portion of the array without having to break it up?

我想知道是否可以只在数组的一部分上使用 .map() 而不必事先分解数组?我知道一个可能的解决方案是保存完整的数据集,并将其分成几部分,然后 .map() 那些部分,但是有没有办法 .map() 一部分数组而不必中断起来了吗?

Any and all feedback is appreciated. Thanks!

任何和所有反馈表示赞赏。谢谢!

回答by Timo

Do not try to solve this problem with a hack in your mapping step.

不要尝试在映射步骤中使用 hack 来解决此问题。

Instead, slice()the list to the right length firstbefore the mapping:

相反,在映射之前slice()首先将列表长度正确

class Feed extends React.Component {
  constructor(props) {
    super(props)
    
    this.handleShowMore = this.handleShowMore.bind(this)
    
    this.state = {
      items: ['Item A', 'Item B', 'Item C', 'Item D'],
      showItems: 2
    }
  }
  
  handleShowMore() {
    this.setState({
      showItems: 
        this.state.showItems >= this.state.items.length ?
          this.state.showItems : this.state.showItems + 1
    })
  }
  
  render() {
    const items = this.state.items.slice(0, this.state.showItems).map(
      (item) => <div>{item}</div>
    )
    
    return (
      <div>
        {items}
        <button onClick={this.handleShowMore}>
          Show more!
        </button>
      </div>
    )
  }
}
  
ReactDOM.render(
  <Feed />,
  document.getElementById('root')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='root'></div>

回答by kevin ternet

If you just want to map a portion of an array, you should first filter() your array to obtain the expected portion according to conditions :

如果你只想映射数组的一部分,你应该首先 filter() 你的数组根据条件获取预期的部分:

array.filter(item => <condition>).map();

回答by Salomao Rodrigues

Array.reduce should do what you're asking for. Just change the if statement depending on which range you want.

Array.reduce 应该做你所要求的。只需根据您想要的范围更改 if 语句。

var excludeAfterIndex = 5;

feed.reduce((mappedArray, item, index) => {
  if (index > excludeAfterIndex) { // Whatever range condition you want
    mappedArray.push(<FeedItem key={index} data={item}/>);
  }

  return mappedArray;
}, []);

回答by Popeye

Yes, you can map portion of array, based on index. For example:

是的,您可以根据索引映射部分数组。例如:

yourArray = yourArray.map(function (element, index, array) {
        if (array.indexOf(element) < yourIndex) {
            return {
               //logic here
            };
        } else {
            return {
                //logic here
            };
        }

    });

回答by dobleUber

you could use the slicefunction before to map the array, it looks like you want to do some pagination there.

您可以在映射数组之前使用slice函数,看起来您想在那里进行一些分页。

var fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'];
var citrus = fruits.slice(1, 3);

// fruits contains ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
// citrus contains ['Orange','Lemon']

回答by Anton v B

There is no version of the map() function that only maps a partial of the array.

没有仅映射部分数组的 map() 函数版本。

You could use .map() in conjunction with .filter().

您可以将 .map() 与 .filter() 结合使用。

You get the index of the current element as the second arg of map and if you have a variable for current page and page size you can quite easily filter the right page from your array without having to really slice it up.

您将当前元素的索引作为地图的第二个参数,如果您有当前页面和页面大小的变量,您可以很容易地从数组中过滤正确的页面,而无需真正将其切片。

var currentPage = 1;
var pageSize = 25;

dataArray.filter(function(elt, index) {

    var upperThreshold = currentPage * pageSize;
    var lowerThreshold = currentPage * pageSize - pageSize;

    return index < upperThreshold && index > lowerThreshold;

});

回答by Nina Scholz

Array#mapiterates over all items.

Array#map迭代所有项目。

The map()method creates a new array with the results of calling a provided function on every element in this array.

map()方法创建一个新数组,其结果是对该数组中的每个元素调用提供的函数。

You could use Array#filter

你可以用 Array#filter

The filter()method creates a new array with all elements that pass the test implemented by the provided function.

filter()方法创建一个新数组,其中包含通过提供的函数实现的测试的所有元素。

for the wanted items and then apply map for the wanted format.

对于想要的项目,然后为想要的格式应用地图。