How to update my associative array while the key already exists else I want to create a new key and store that array in the state. I had tried to store a value in the associative array. When I entering data in the input field it can call handleChange
after that I want to do that above I mentioned operations
import React, { Component } from 'react';
class App extends Component {
constructor(props) {
super(props);
this.onChangeEvent = this.onChangeEvent.bind(this);
this.onChangeCount = this.onChangeCount.bind(this);
this.onSubmit = this.onSubmit.bind(this);
this.state = {
name: [],
inputCount:5
}
}
// associtive array
handleChange = (e) => {
// I want to check the key is already exist or not if exist means create update the value else create a new key and also I want to validate all the data.
const check = e.target.name
const value = e.target.value
const name = []
name[check] = value
console.log(name)
this.setState({
name,
})
}
render() {
let options = []
for (let i = 0; i < this.state.inputCount; i += 1) { options.push(i); }
return (
{this.state.inputCount && (
options1.map((i) => {
return (<div key={i}>
<input onChange={this.handleChange} type="text" className="name" name={`name${i}`} placeholder="Name" /><br />
</div>)
})
)}
);
}
}
export default App;
First, there are no "associative arrays" in JavaScript, though there are Objects, which is basically the same. So right off the bat, you should change the initialization of name
to be {}
instead of []
.
To check if a key exists in an Object, simply do check in obj
or even name.hasOwnProperty(check)
, where check
is the key you want to check.
Setting and updating a value is done the same way in JavaScript, regardless if the key exists or not: name[check] = value
.
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.