如何在Javascript中检查唯一性?

时间:2015-08-20 13:25:44

标签: javascript jquery arrays json

我有一个下拉菜单。

enter image description here

JS

$.each(responseData.assignments, function(i, v) {

    var assessmentId = v.assessmentId;
    var assessmentType = v.assessmentType;

    // Auto Populate the dropdown-menu
    $('#student-dd').append('<option value="' + assessmentId + '">' + assessmentType + '</option>');

});

目标 我想只展示一个HOMEWORK / COURSE_BENCHMARK,并不是有多少人在那里。如何在Javascript中检查唯一性?

2 个答案:

答案 0 :(得分:3)

您可以在添加新内容之前使用过滤器功能检查该下拉列表中具有相同文本的选项元素的长度:

$.each(responseData.assignments, function(i, v) {

  var assessmentId = v.assessmentId;
  var assessmentType = v.assessmentType;

  // Auto Populate the dropdown-menu

  var optionwithsametext = $('#student-dd option').filter(function(){
      return $(this).text() == assessmentType ;
  })
  if(!optionwithsametext.length)
    $('#student-dd').append('<option value="' + assessmentId + '">' + assessmentType + '</option>');

 });

答案 1 :(得分:1)

有多种方法可以做到这一点。这是另一个例子;

var assignments = {};
$.each(responseData.assignments, function(i, v) {
    assignments[v.assessmentType] = v.assessmentId;
});

$.each(assignments, function(i, v) {
    // Auto Populate the dropdown-menu
    $('#student-dd').append('<option value="' + v + '">' + i + '</option>');
});