javascript selectize js 使用数组作为源
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19236981/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
selectize js use array as source
提问by Athanatos
Hi I am getting back a JSON encoded array ("html") from my Ajax call that I would like to add in the selectize as both value and text (I am using a tag) . How can I do that ?
嗨,我从我的 Ajax 调用中取回了一个 JSON 编码的数组(“html”),我想将它作为值和文本(我正在使用标签)添加到 selectize 中。我怎样才能做到这一点 ?
HTML
HTML
<input type="text" value="test" class="demo-default selectized" id="input-tags" tabindex="-1" style="display: block;">
JQUERY
查询
try {
data = $.parseJSON(html);
var obj = jQuery.parseJSON(html);
outcome = (obj.outcome);
$('#input-tags').selectize({
delimiter: ',',
persist: false,
maxItems: 1,
create: function (input) {
return {
value: input,
text: input
}
}
});
}
}
回答by McGarnagle
You could map the array onto an array of objects, like this:
您可以将数组映射到对象数组,如下所示:
data = $.parseJSON(html);
var items = data.map(function(x) { return { item: x }; });
Then use "labelField" and "valueField"to specify the text/value:
然后使用“labelField”和“valueField”来指定文本/值:
$('#input-tags').selectize({
delimiter: ',',
persist: false,
options: items,
labelField: "item",
valueField: "item"
});
回答by Grégory Copin
With ES6 you can reduce your oneliner a bit
使用 ES6 你可以减少你的单行代码
const items = data.map(item => ({item}));