我试图映射一个数组,并在数组中找到对象的索引

时间:2016-10-06 19:50:14

标签: dictionary reactjs jsx react-bootstrap

我有一个组件,我想在对象数组中找到索引(现在我有一个硬编码的对象数组,但后来会使用调用来获取数据)。我想在数组的每第五个位置添加一个2的mdOffset。我该怎么做呢?我的代码:

export default class Winks extends Component {
  constructor () {
    super()
    this.state ={
      items: [
        { id:1, name: "The Kooples - white top", url:"bloomingdales.com", src: "assets/male.png" },
        { id:2, name: "Sandro-Orange Zipper",  url:"saksfifth.com", src: "assets/female.png" },
        { id:3, name: "Sandro-Orange Zipper",  url:"saksfifth.com", src: "assets/female.png" },
        { id:4, name: "Sandro-Orange Zipper",  url:"saksfifth.com", src: "assets/female.png" },
        { id:1, name: "Sandro-Orange Zipper",  url:"saksfifth.com", src: "assets/female.png" },
        { id:1, name: "The Kooples - dress",  url:"bloomingdales.com", src: "assets/male.png" },
        { id:1, name: "The Kooples - dress",  url:"bloomingdales.com", src: "assets/male.png" },
      ]
    }
  }

  render () {

    var listItems = this.state.items.map.bind(this)(function(item) {
      if (this.state.items.indexOf(item) % 5 === 0 ) {
        var columns = (
          <Col md={2} mdOffset={2}>
              <img className='img-responsive' src={item.src}></img>
            <Row>
              <span>{item.name}</span>
            </Row>
            <Row className="pull-right">
              <i className="fa fa-heart"></i>
            </Row>
          </Col>
        )
      }

      else {
        var columns = (
          <Col md={2}>
              <img className='img-responsive' src={item.src}></img>
            <Row>
              <span>{item.name}</span>
            </Row>
            <Row className="pull-right">
              <i className="fa fa-heart"></i>
            </Row>
          </Col>
        )
      }

      return columns
    });

    return (
        <Row>
          {listItems}
        </Row>
    )
  }
}

1 个答案:

答案 0 :(得分:2)

映射时,将元素的索引作为第二个参数https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

例如:

arr.map(function(item, index) {
  if (index % 5 === 0) {
    // do your stuff here
  }
});

或者

arr.map(function(item, index) {
  <Col mdOffset={index % 5 === 0 ? 2 : null}>

  </Col>
});