React - how to add dynamic key/value pair to an object?
14,413
You can accomplish what you want using computed expression (I'm not really sure if you are trying to do that already). So your appendInput
function should look something like this:
appendInput() {
var objectSize = Object.keys(this.state.milestonesValues).length;
var newInput = Object.assign({},
this.state.milestonesValues, {['milestone'+ objectSize]: ''});
this.setState({
milestonesValues: newInput)
});
}
Author by
Jakub Kašpar
Updated on June 04, 2022Comments
-
Jakub Kašpar almost 2 years
I am trying to add dynamic key/value pair to an initial object with the appendInput() function.
Initial object:
constructor(props) { super(props); this.state = { milestonesValues : { milestone0: "dssdsad", milestone1: "", milestone2: "", milestone3: "", } };
}
The render method:
render(){ return( <div> <main className="content"> <form onSubmit={this.onSubmit}> <div className="input-wrap"> <label>{'What are the basic steps?'} {Object.keys(this.state.milestonesValues).map( (milestone, index) => <input key={milestone} placeholder={`${index+1}.` } type="text" name={milestone} value={this.state.milestonesValues[milestone]} onChange={this.handleInputChange} /> )} </label> <button onClick={ () => this.appendInput() }> {"+ ADD MILESTONE"} </button> </div> </form> </main> </div> );
appendInput() function:
appendInput() { var objectSize = Object.keys(this.state.milestonesValues).length; var newInput = `milestone${objectSize}: "",`; console.log(newInput); this.setState({ milestonesValues: this.state.milestonesValues.concat([newInput]) });
}
and I just can't add the new generated key/value to that initial object.
Can someone help, please?
-
ᴄʀᴏᴢᴇᴛ over 5 yearswhile this code may answer the question, adding some explanations on why and how would improve the quality of the answer