如何在数组中查找对象并在 React 组件中显示它?

Jac*_*ack 4 javascript reactjs

我有很多城市都有这样的物体:

[{id: 1, name: 'New York'}, {id: 2, name: 'London'} ...]
Run Code Online (Sandbox Code Playgroud)

我的值是id

我将数组中的元素(名称)放入选择列表。但我需要添加第一个选项,其中包含数组(名称)中的值,该选项具有相应的 id,但我无法使其工作。

我的组件:

const propTypes = {  
  cities: PropTypes.array,  
  enteredEvent: PropTypes.array  
};

class newEvent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      showInOption: ''
    };
    this.handleDictionary = this.handleDictionary.bind(this);
    this.searchTypeEvent = this.searchTypeEvent.bind(this);
  }

  componentDidMount() {
    this.searchTypeEvent();
  }

  handleDictionary(e) {
    ...
  }

  searchTypeEvent() {
    if (this.props.enteredEvent.cityid !== null && this.props.enteredEvent.cityid !== undefined) { // if I have id value
      const type = this.props.cities.find(el => el.id === this.props.enteredEvent.cityid); // find an object with id
      this.setState({ showInOption: type.name });
    }
    this.setState({ showInOption: 'Select something' });
  }

  render() {
    return (
      <div>       
        <select onChange={this.handleDictionary}>
          <option>{this.state.showInOption}</option> // here I need to add a value
          {this.props.cities.map(item => {   // here I call other options
            return (<InputSelect key={item.id} directory={item}/>);
          })}
        </select>        
      </div>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

我有一个错误:

未捕获的类型错误:无法读取未定义的属性“名称”

我该如何修复它?

brk*_*brk 6

看来你需要过滤器。它将返回一个对象数组

let a = [{
  id: 1,
  name: 'New York'
}, {
  id: 2,
  name: 'London'
}]

function b(idToSearch) {
  return a.filter(item => {
    return item.id === idToSearch
  })
};

console.log(b(1))
Run Code Online (Sandbox Code Playgroud)