Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
115
rated 0 times [  117] [ 2]  / answers: 1 / hits: 27221  / 6 Years ago, tue, november 13, 2018, 12:00:00

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?


More From » reactjs

 Answers
77

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




[#53120] Thursday, November 8, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
magdalena

Total Points: 364
Total Questions: 101
Total Answers: 92

Location: Namibia
Member since Mon, Nov 14, 2022
2 Years ago
;