Home > database >  How to render a list of object in react getting the key and the value
How to render a list of object in react getting the key and the value

Time:11-30

const data = {
  "070010": "ABBEY MORTGAGE BANK-070010",
  "044": "ACCESS BANK PLC-044",
  "323": "AccessMobile-100013",
}

How can I render the value of the data above in a select tag and on Change on each I will get the key and value.

const [acctname,setAcctname]=useState("")
for (const key in data) {
  if (Object.hasOwnProperty.call(data, key)) {
    const element = data[key];
    setAcctName(Object.values(data))
    
  }
}

return (
<select>
   <option >{acctName}</option>
</select>

)

but not working

CodePudding user response:

As you are creating array of your data object in acctname state, you need to write a loop to display that array data. Try this:

import { useEffect, useState } from 'react';

const data = {
  "070010": "ABBEY MORTGAGE BANK-070010",
  "044": "ACCESS BANK PLC-044",
  "323": "AccessMobile-100013",
}

const App = () => {
  const [acctname, setAcctname] = useState("");

  useEffect(() => {
    for (const key in data) {
      if (Object.hasOwnProperty.call(data, key)) {
        const element = data[key];
        setAcctname(Object.values(data));
      }
    }
  }, []);

  const handleChange = (acc) => {
    console.log("Selected option: ", acc)
  }

  return (
    <div>
      {acctname && <select onChange={(e) => handleChange(e.target.value)}>
        {acctname.map((acc, i) => (
          <option key={i}>{acc}</option>
        ))}
      </select>}
    </div>
  )
}

CodePudding user response:

Try this for your specific key selection:

import { useEffect, useState } from 'react';

const data = {
  "070010": "ABBEY MORTGAGE BANK-070010",
  "044": "ACCESS BANK PLC-044",
  "323": "AccessMobile-100013",
}

const App = () => {
  const [acctname, setAcctname] = useState("");

  useEffect(() => {
    const entries = Object.entries(data);
    const arraySet = [];
    for (const key in entries) {
      const set = entries[key];
      arraySet.push(`${set[0]}: ${set[1]}`);
    }
    setAcctname(arraySet);
  }, []);

  const handleChange = (acc) => {
    let selectedOpt = acctname.filter(val => val.includes(acc))[0]?.split(":");
    console.log("Selected option key: ", selectedOpt[0]);
    console.log("Selected option value: ", selectedOpt[1]);
  }

  return (
    <div>
      {acctname.length && <select onChange={(e) => handleChange(e.target.value)}>
        {acctname.map((acc, i) => {
          let set = acc.split(":");
          return (
            <option key={i}>{set[1].trim()}</option>
          )
        }
        )}
      </select>}
    </div>
  )
}
  • Related