从对象数组创建选项元素

时间:2019-02-21 12:09:51

标签: javascript jquery html

我想过滤subject中的值,并使用Javascript在HTML的option标签中显示它们。我该怎么办?

var user = [{
  "id": 1,
  "firstname": "kalpit",
  "lastname": "dwivedi",
  "age": 20,
  "hometown": "jhansi",
  "job": "web design",
  "subject": ["Hindi", "English"]
}, {
  "id": 2,
  "firstname": "golu",
  "lastname": "gupta",
  "age": 30,
  "hometown": "Vadodara",
  "job": "qa tester",
  "subject": ["Hindi", "Socilogy"]
}, {
  "id": 3,
  "firstname": "john",
  "lastname": "doe",
  "age": 35,
  "hometown": "newport",
  "job": "oprater",
  "subject": ["English", "Socilogy"]
}, {
  "id": 4,
  "firstname": "mohit",
  "lastname": "khare",
  "age": 40,
  "hometown": "kochi",
  "job": "civil",
  "subject": ["infa", "angularjs"]
}

1 个答案:

答案 0 :(得分:0)

这是一些数据的示例...如果您想动态地进行操作,则必须对jquery进行$.each

让我知道这是否是您想要的。

var data = '{"id":2, "firstname":"golu", "lastname":"gupta", "age":30, "hometown":"Vadodara", "job":"qa tester", "subject" : ["Hindi", "Socilogy"]}';

    var dataParse = JSON.parse(data);
    console.log(dataParse.subject);
    $(document).ready(function(){

        $('#opt1').html(dataParse.subject[0]);
        $('#opt2').html(dataParse.subject[1]);
    });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
 <select name="data" id="data">
        <option value="" id="opt1"></option>
        <option value="" id="opt2"></option>
 </select>