jessiexx
jessiexx

Reputation: 11

How to list objects in a JSON file in html select options using only javascript?

Firstly, my javascript knowledge is very very low and I'm struggling quite a bit hence the question. I understand there have been many similar questions, but what I need is for it to only use very basic javascript. So far I have:

JSON File:

var list=
    [
      {"title":"ObjectA",...
      },
      {"title":"ObjectB",...
      }
    ]

I've managed to list them using:

function objects() {
                for (a=0; a<list.length; a++) {
                    document.write(list[a].title);
                }
            }

However that puts all objects in one line. I know you can list them individually using something like:

function object0() {
                document.write(list[0].title)
            }

What I'm wondering is it is possible to list them using a for loop or something simple like that? Thanks in advance for any help.

Upvotes: 1

Views: 38

Answers (2)

num8er
num8er

Reputation: 19372

Simple!

var list=
    [
      {"title":"ObjectA"},
      {"title":"ObjectB"},
      {"title":"ObjectC"},
      {"title":"ObjectD"},
      {"title":"ObjectE"},
      {"title":"ObjectF"}
    ];

document.write('<select name="item">');
list.map(function(item) {
  document.write('<option>'+item.title+'</option>');
});
document.write('</select>');

Upvotes: 1

Mati
Mati

Reputation: 1148

Try this:

const pre = document.createElement("pre");
pre.innerHTML = JSON.stringify(list, null, 2);
document.body.appendChild(pre);

or print it to the console

console.log(JSON.stringify(list, null, 2));

Working example:

const list = [
  { 'title': 'ObjectA' },
  { 'title': 'ObjectB', foo: { ble: 123 } }
]

const pre = document.createElement('pre');
pre.innerHTML = JSON.stringify(list, null, 2);
document.body.appendChild(pre);
<body>
</body>

Upvotes: 1

Related Questions