简体   繁体   中英

map 2 array of object using findIndex es6

I have 2 array of object, one is the preloaded list, one is the selected items. My problem is couldn't make the selected items checked on checkboxes.

https://jsfiddle.net/8usvfzv9

class HelloWidget extends React.Component {
    constructor(props) {
      super(props);
      this.list = [{
        "id": "exhibitions",
        "name": "Exhibitions"
      }, {
        "id": "festivals_n_concerts",
        "name": "Festivals & Concerts"
      }, {
        "id": "grand_opening",
        "name": "Grand Opening"
      }, {
        "id": "meeting",
        "name": "Meeting"
      }, {
        "id": "party",
        "name": "Party"
      }, {
        "id": "product_launches",
        "name": "Product Luanches"
      }, {
        "id": "roadshows",
        "name": "Roadshows"
      }, {
        "id": "sporting_events",
        "name": "Sporting Events"
      }, {
        "id": "trade_show",
        "name": "Trade Show"
      }]

      this.selectedList = [{
        "id": "grand_opening",
        "name": "Grand Opening",
        "space_event_id": "grand_opening"
      }, {
        "id": "trade_show",
        "name": "Trade Show",
        "space_event_id": "trade_show"
      }]
    }

    render() {
        return (<div>
        {this.list.map(obj => <div><br /><input 
        key={obj.name}
        checked={this.selectedList.findIndex(o => o.id === obj.id)}
        type="checkbox" >{obj.name}</input></div>)}
        </div>
        )
        }
}

I think this line is wrong

checked={this.selectedList.findIndex(o => o.id === obj.id)}

base on the output result. Any clue how to use findIndex?

由于“选中” 属性仅适用于布尔值,并且findIndex返回数字,因此您可以进行如下修改:

checked={this.selectedList.findIndex(o => o.id === obj.id) !== -1}

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