Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically add values ​of an object into inputs in two rows using array method forEach

I have an object with several keys and values, I would like to add its values ​​to inputs corresponding to the key of the object. But I want to do this dynamically and generically using a method of array (forEach) in a two line code.

My object:

const createNewBill = {
  type: "Hôtel et logement",
  name: "bill test",
  date: "2020-04-08",
  amount: 130,
  pct: 25,
  file: 'hotel.jpg'
}

I found this way but it is not dynamic and scalable :

document.getByTestId("expense-type").value = createNewBill.type
document.getByTestId("expense-name").value = createNewBill.name
document.getByTestId("datepicker").value = createNewBill.datepicker
document.getByTestId("amount").value = createNewBill.amount
document.getByTestId("pct").value = createNewBill.pct
document.getByTestId("file").value = createNewBill.file 
like image 353
Willem JOURET Avatar asked Oct 19 '25 03:10

Willem JOURET


2 Answers

const createNewBill = {
  type: "Hôtel et logement",
  name: "bill test",
  date: "2020-04-08",
  amount: 130,
 }

 Object.keys(createNewBill).forEach(key => {
   document.getElementById(key).value = createNewBill[key]
 });
<!DOCTYPE html>
<html lang="en">
    <body>
        <input id="type" />
        <input id="name" />
        <input id="date" />
        <input id="amount" />
    </body>
</html>

One solution that I can suggest if you could change the keys of the object to the same ones in your HTML IDs or vice versa.

Object.keys(createNewBill).forEach(key => {
  document.getByTestId(key).value = createNewBill[key]
});
like image 159
Rami Shahazeh Avatar answered Oct 20 '25 18:10

Rami Shahazeh


I'm guessing that something like could work:

Object.entries(createNewBill).forEach(([key, value]) =>
  document.getByTestId(key).value = value);

But it would require you to rename expense-type into type and same for expense-name and datepicker. Or to use the same prefix for all the other ones.

Anyway, I strongly recommend you to use a lib like ReactJS, Angular or anything that will make this king of things easier for you!

like image 29
Xavier Garnier Avatar answered Oct 20 '25 18:10

Xavier Garnier