Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find object in array and show it in React component?

I have array of cities with objects like this:

[{id: 1, name: 'New York'}, {id: 2, name: 'London'} ...]

and I have a value of id.

I put elements (names) from array to select list. But I need to add first option with value from array (name) which have the corresponding id which I can't make it work.

My component:

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>
    );
  }
}

I have an error:

Uncaught TypeError: Cannot read property 'name' of undefined

How can I fix it?

like image 490
Jack Avatar asked Jan 28 '23 04:01

Jack


2 Answers

It seems you need filter.It will return an array of object

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))
like image 106
brk Avatar answered Jan 29 '23 16:01

brk


Try this

  const type = Array.isArray(this.props.cities) && this.props.cities.find(el => el.id ==this.props.enteredEvent.cityid);
  this.setState({ showInOption: type ? type.name : null });

Make sure the name you enter matches with any one of the object in array

like image 31
Hemadri Dasari Avatar answered Jan 29 '23 18:01

Hemadri Dasari