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

Time:10-26

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 

CodePudding user response:

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!

CodePudding user response:

You can achieve this by using Object.keys() method along with the Template literals (Template strings) syntax.

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

Object.keys(createNewBill).forEach(key => {
    document.getByTestId(`expense-${key}`).value = createNewBill[key]
})

CodePudding user response:

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]
});
  • Related