因此,我正在使用Algolia的即时搜索并且很喜欢它,但是却遇到了一个问题。我的数据库模型有一个多态关联,每个tag
都存储在一个数组中,我只想将所有标记显示为一个字符串,但是我不知道该怎么做。我已经尝试获取tag_list.value,但是那没有用,其他所有东西都变得不确定。
<script>
var client = algoliasearch("xxxxx", "xxxx");
var index = client.initIndex('myname');
//initialize autocomplete on search input (ID selector must match)
autocomplete('#aa-search-input',
{ hint: false }, {
source: autocomplete.sources.hits(index, {hitsPerPage: 25}),
//value to be displayed in input control after user's suggestion selection
displayKey: 'name',
//hash of templates used when rendering dataset
templates: {
//'suggestion' templating function used to render a single suggestion
suggestion: function(suggestion) {
return '<span class="aa-highlight">' +
suggestion._highlightResult.tag_list.value +
suggestion._highlightResult.question.value + '</span><span>' +
suggestion._highlightResult.answer_explanation.value + '</span>';
}
}
});
</script>
tag_list是一个数组,但是我不知道如何在JavaScript中访问json数组。我尝试了.stringify和.arr [0],但不确定。
suggestion._highlightResult.tag_list.value +
这是我遇到问题的代码/代码行。
答案 0 :(得分:1)
关注arieljuod的评论,这将有助于了解返回的suggestion._highlightResult.tag_list.value
类型。话虽这么说,希望对您有所帮助。
在JavaScript中,您可以通过在数组上调用Team Share方法来将数组转换为字符串。
单项数组
var array = ["item 1"];
array.join(); // Output: "item 1"
多项数组
var array = ["item 1", "item 2"];
array.join(); // Output: "item 1,item 2"
自定义分隔符
默认情况下,join
方法使用“,”作为分隔符数组。如果您想使用其他方式,则可以将字符串传递给join
函数:
var array = ["item 1", "item 2"];
array.join("/"); // Output: "item 1/item 2"
我m包括了这一点,因为我不确定suggestion._highlightResult.tag_list.value
返回的是哪种数据类型。
如果tag_list.value
返回的值是一个包含JSON的字符串(即{{1} },则可以使用join
将其转换为JavaScript数组:
"[\"item 1\", \"item 2\"]"