Mr.Gomer
Mr.Gomer

Reputation: 649

Populating object values with a Array (React hooks)

Im creating a medical app and i got a react class that uses hooks and looks like this.

  const ToggleSwitch = () => {
  const API_URL = "http://localhost:8081/api/doh/";
  const [medications, setMedications] = useState("");
  const [otherInfo, setOtherInfo] = useState("");

  const [values, setValues] = useState({
    asthma: "off",
    infectiousDisease: "off",
    bleedingDisorder: "off",
    cancer: "off",
    diabetes: "off",
    epilepsy: "off",
    stroke: "off",
    heartDisease: "off",
    hbp: "off",
    immuneDisorders: "off",
    lungDisease: "off",
    mentalDisorder: "off",
    rheumaticDisease: "off",
    smokeTobaccoProducts: "off",
    radiationTherapy: "off",
    eatingDisorders: "off",
    entDisorders: "off",

    latex: "off",
    localAnasthetics: "off",
    metals: "off",
    penicillin: "off",
    pollen: "off",
    foods: "off",

    bleedingGums: "off",
    bruxism: "off",
    halitosis: "off",
    ulcer: "off",
    dryMouth: "off",
    soreJawM: "off",
  });

  const handleChangeMed = (e) => {
    setMedications(e.target.value);
  };

  const handleChangeOtherInfo = (e) => {
    setOtherInfo(e.target.value);
  };

My backend returns an Array(witchValues: Array(30)) with values (off/on) for each of the values as they are used with switches. Now my question is, is there any way to populate these values in a fast way like say with a foreach loop or anything like that, rather than taking one value at a time from the Array and adding it to the individual values in the switch?

Side note i cant change the switch to an array as that does not fit my purpose when it comes to other methods that work on the switch.

Ps.The input array only contains the values it looks like this: witchValues: Array(30) 0: "off" 1: "off" 2: "off" 3: "off" 4: "off" 5: "off" 6: "off" 7: "off" 8: "off" 9: "off" 10: "on" 11: "off" 12: "off" 13: "off" 14: "off" 15: "off" 16: "off" 17: "off" 18: "off" 19: "off" 20: "off" 21: "off" 22: "off" 23: "off" 24: "off" 25: "off" 26: "off" 27: "off" 28: "off" 29: "on" length: 30

Upvotes: 0

Views: 97

Answers (1)

La Quoc Anh
La Quoc Anh

Reputation: 121

let newValues = values // create a variable of value
// turn newValues into entries. 
// example {asthma: "off", cancer: "off"} => [['asthma', 'off'], ['cancer', 'off']]
// now you can map through each property of the object
let valueArray = Object.entries(newValues).map((v, index) => {
    v[1] = switchValues[index]
    return v
}
// turn entries back to object
newValues = Object.fromEntries(valueArray)
// set back into state
setValues({...newValues})

Upvotes: 1

Related Questions