简体   繁体   中英

ReactJS set dynamic input value based on Object

I have an Object like this:

在此处输入图片说明

And an object like this:

const subjectQuantities = {
      9: 2,
      11: 1,
    };

Where 9 and 11 are similar to the object id of first Object what I want to do is set the value of an input field dynamically so what I did is this:

{ Object.keys(subjects).map((item, i) => (
   <li className="travelcompany-input clearfix" key={i}>
      <span className="input-label">{ subjects[item].name }</span>
         <div className="input-group">
           { subjects[item].id in subjectQuantities ?
            <input className="form-control form-travelcompany-input" type="text" value=*DYNAMIC VALUE* min="0" max="10" />
             : <p>TEST</p>
             }
         </div>
   </li>
))} 

How do I set the value of this input field dynamically based on the value of the subjectQuantities object.

If i understand your question correctly you just need to do {subjectQuantities[item]}

See your example below.

{ Object.keys(subjects).map((item, i) => (
   <li className="travelcompany-input clearfix" key={i}>
      <span className="input-label">{ subjects[item].name }</span>
         <div className="input-group">
           { subjects[item].id in subjectQuantities ?
            <input className="form-control form-travelcompany-input" type="text" value={subjectQuantities[item]} min="0" max="10" />
             : <p>TEST</p>
             }
         </div>
   </li>
))} 

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM