循环遍历对象内的数组并将ID吐出到下拉列表中

时间:2018-01-07 12:43:13

标签: javascript jquery arrays

打扰一下,如果这个问题已经得到解答,我确信它有,但找不到我理解的例子。

我想要完成的是循环并将ID吐出到下拉列表中。

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));
});

4 个答案:

答案 0 :(得分:2)

不确定您是否希望将更多数据添加到option,但这是您之后的目标。

&#13;
&#13;
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);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<select id="dropdown"></select>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

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>

答案 2 :(得分:1)

<强>样本

&#13;
&#13;
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);
 });
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="dropdown"> 
</select>
&#13;
&#13;
&#13;

答案 3 :(得分:-1)

let ids = things.list.map(function(item){
    return item.id
});

这适用于ES6