我有一个JSON字符串,希望添加到select2多选搜索输入中。我收到以下地图错误


  无法读取未定义的属性“地图”


控制台日志中的json字段是

[{"id":1,"name":"Test Test"},{"id":2,"name":"Billy A"}]


js代码是

   var employees = $(this).attr('data-employees');
    console.log(employees);

    $("select[name='employees[]']").val(employees.data.map(function(x) {
   return x.id; })); // Set the selected data before show it.
            $('select').select2()


的HTML

<select multiple="multiple" name="employees[]" id="form-field-select-4" width="200px "class="form-control search-select"></select>

最佳答案

如我所见,您是从element属性获取此数组的,如果是,则console.log可能是字符串,因此请尝试以下操作:

var employees = JSON.parse( $(this).attr('data-employees') );
console.log(employees);

$('select').select2(); // init with select2
$("select[name='employees[]']").val(employees.map(function(x) {
   return x.id;  // Set the selected data before show it.
}))
.trigger("change");


如果看到这个



var employees = JSON.parse('[{"id":1,"name":"Test Test"},{"id":2,"name":"Billy A"}]');
console.log('The whole array:', employees); // you have a valid array

var ids = employees.map(function(x){ return x.id; })
console.log('Employee ids only: ', ids);





已编辑

09-25 20:09