简体   繁体   中英

Populating form fields from JSON feed using forEach or for loop (JS)

I have form fields like these

<input id="first">
<input id="second">
<textarea id="third"></textarea>
...

and I need to dynamically populate them with data from a JSON feed. Each field's id corresponds to each JSON's key , so I'm able to populate those fields this way:

first.value = feed.first;
second.value = feed.second;
third.value = feed.third;
...

But I would like to make it simpler.

This is what I've tried:

["first", "second", "third"].forEach(e => {e.value = feed[e]});

Sadly, it doesn't work. In console I can see JSON feed's values ( feed[e] ), but form fields are blank.

What am I doing wrong?

Any suggestions would be much appreciated.

Please use eval function.

["first", "second", "third"].forEach(e => {eval(e).value = feed[e]});

You can try using document.getElementById to get specific DOM element
and then assign the value you want.

const feed = {
    'first': 'hello',
    'second': 'word',
    'third': '!'
};

['first', 'second', 'third'].forEach(e => {
    document.getElementById(e).value = feed[e]
});

The link below is a full demonstration.
https://jsfiddle.net/2x0o8d4m/1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM