Reputation:
Excuse me if this question has already been answered as I am sure it has but cannot find an example I understand.
What I am trying to accomplish is to loop over and just spit out the ids into a dropdown.
const things = {
"list": [{
"id": "123456",
"name": "Jack Smith"
},
{
"id": "789101",
"name": "Ellie Cocks"
},
{
"id": "535253",
"name": "Peter Johns"
},
{
"id": "9353638",
"name": "Anna Jacobs"
}
]}
$.each(things, function() {
$('#dropdown').append($("<option />").text(things.list.id));
});
Upvotes: 2
Views: 54
Reputation: 6699
const things = {
"list": [{
"id": "123456",
"name": "Jack Smith"
},
{
"id": "789101",
"name": "Ellie Cocks"
},
{
"id": "535253",
"name": "Peter Johns"
},
{
"id": "9353638",
"name": "Anna Jacobs"
}
]}
things.list.map(function(elem) {
$('#dropdown').append($('<option/>',{value:elem.id,text:elem.name}));
});
$(document).on("change","#dropdown",function(){
console.log($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="dropdown"></select>
Upvotes: 2
Reputation: 236
let ids = things.list.map(function(item){
return item.id
});
This will work in ES6
Upvotes: -1
Reputation: 11297
Not sure if you want more data to be added to option
but this is what you're after.
const select = $('#dropdown');
const things = {
"list": [{
"id": "123456",
"name": "Jack Smith"
},
{
"id": "789101",
"name": "Ellie Cocks"
},
{
"id": "535253",
"name": "Peter Johns"
},
{
"id": "9353638",
"name": "Anna Jacobs"
}
]
}
$.each(things.list, (i, item) => {
let opt = $("<option />", {
value: item.id,
text: item.name
});
select.append(opt);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<select id="dropdown"></select>
Upvotes: 2
Reputation: 222712
DEMO
const things = {
"list": [{
"id": "123456",
"name": "Jack Smith"
},
{
"id": "789101",
"name": "Ellie Cocks"
},
{
"id": "535253",
"name": "Peter Johns"
},
{
"id": "9353638",
"name": "Anna Jacobs"
}
]}
$.each(things.list, function(val, text) {
var data = '<option>' + things.list[val].id + '</option>'
$('select').append(data);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="dropdown">
</select>
Upvotes: 1