繁体   English   中英

我如何在React JS中使用Lodash获取特定的数组

[英]How can i get the specific array using Lodash in react js

我如何在React js中使用Lodash获得特定的数组? 我有一个对象数组,10个topUsers。

data:{
 "topUsers":[
   {
      "user":"foo"
   },
   {
      "user":"bar"
   },
   {
      "user":"mike"
   },
   {
      "user":"jen"
   },
   {
      "user":"carl"
   },
   {
      "user":"ben"
   },
   {
      "user":"tony"
   },
   {
      "user":"mark"
   },
   {
      "user":"peter"
   },
   {
      "user":"jake"
   }
]}

我想显示从前5位开始的“ user”:“ carl”,假设{idx}是数组的索引

我尝试使用_.map映射数据,但是对于特定的索引或数组,我没有任何想法。

<TableBody displayRowCheckbox={false} style={{minHeight: 65}}>
{ _.map(this.state.data.topUsers, (users, idx) => { return(
<TableRow displayBorder={true}>
    <TableRowColumn style={{height: 75 , textAlign: 'center'}}>{idx + 1}</TableRowColumn>
    <TableRowColumn style={{ justifyContent: 'center', textAlign: 'center' , paddingLeft: '5px' }}>
        <Col xs={12}>
            <Row>
                <Col xs={4} style={{display: 'flex', justifyContent: 'center', alignItems: 'center'}}>
                    <label style={{whiteSpace: 'normal', overflow: 'hidden', textOverflow: 'ellipsis'}}>
                        {_.get(users, 'users', ' ')}
                    </label>
                </Col>
            </Row>
        </Col>
    </TableRowColumn>
</TableRow>) })}

您可以尝试_.slice(array, [start=0], [end=array.length])要了解更多信息,请参见此处输入链接描述

您可以使用Array#slice (或lodash的等效项)将数组从索引切成末尾。 因此arr.slice(4)将创建一个从第5个(从0开始)到末尾的新数组。

顺便说一句-如果您想获得5个热门项目,则需要从索引5中进行切片。从第4个索引中进行切片将为您提供6个项目。

例如:

 const topUsers = [{"user":"foo"},{"user":"bar"},{"user":"mike"},{"user":"jen"},{"user":"carl"},{"user":"ben"},{"user":"tony"},{"user":"mark"},{"user":"peter"},{"user":"jake"}]; const result = topUsers.slice(5) .map(({ user }) => user); // whatever you want to map user into console.log(result); 

在您的情况下:

<TableBody displayRowCheckbox={false} style={{minHeight: 65}}>
{ this.state.data.topUsers.slice(5).map((users, idx) => { return(
<TableRow displayBorder={true}>
    <TableRowColumn style={{height: 75 , textAlign: 'center'}}>{idx + 1}</TableRowColumn>
    <TableRowColumn style={{ justifyContent: 'center', textAlign: 'center' , paddingLeft: '5px' }}>
        <Col xs={12}>
            <Row>
                <Col xs={4} style={{display: 'flex', justifyContent: 'center', alignItems: 'center'}}>
                    <label style={{whiteSpace: 'normal', overflow: 'hidden', textOverflow: 'ellipsis'}}>
                        {_.get(users, 'users', ' ')}
                    </label>
                </Col>
            </Row>
        </Col>
    </TableRowColumn>
</TableRow>) })}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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