0

I wrote the following code, which works finely:

    document.getElementById('firstName').value = persons[checkboxId].firstName;
    document.getElementById('lastName').value = persons[checkboxId].lastName;
    document.getElementById('street').value = persons[checkboxId].street;
    document.getElementById('zipCode').value = persons[checkboxId].zipCode;
    document.getElementById('city').value = persons[checkboxId].city;
    document.getElementById('mobile').value = persons[checkboxId].mobile;
    document.getElementById('email').value = persons[checkboxId].email;

Now I want to write this code more clearly using a loop. So I tried this:

let inputFields = ['firstName', 'lastName', 'street', 'zipCode', 'city', 'mobile', 'email'];

    for (let i = 0; i < inputFields.length; i++) {
      document.getElementById(inputFields[i]).value = persons[checkboxId].inputFields[i];
    }

But it doesn't work. The problem is with // persons[checkboxId].inputFields[i] // I get an "Cannot read properties" - error.

Persons is a JSON like this:

let persons = [
    {
        firstName : 'ABC',
        lastName : 'DEF'
    },
    {
        firstName : 'CHG',
        lastName : 'KJI'
    }
]

Is there a way to read the properties using a loop?

Thank you very much for help!

  • 1
    Please [search thoroughly](/search?q=%5Bjs%5D+object+property+variable) before posting, there are questions about this, with answers or links to answers, on the very first page of results. More about searching [here](/help/searching). – T.J. Crowder Mar 01 '23 at 10:29
  • Just FYI, JSON is a *textual notation* for data exchange. [(More here.)](http://stackoverflow.com/a/2904181/157247) If you're dealing with JavaScript source code, and not dealing with a *string*, you're not dealing with JSON. – T.J. Crowder Mar 01 '23 at 10:33

0 Answers0