Javascript Jquery只推送到对象的唯一元素
我有这样的代码:Javascript Jquery只推送到对象的唯一元素,javascript,jquery,Javascript,Jquery,我有这样的代码: var leadNamesForAutocomplete=[]; $('#filterByNameAutosuggestion option').each(function () { leadNamesForAutocomplete.push({label: $(this).text(), value: $(this).val()}); }); 如何将LeadNames推送到仅自动完成唯一标签?您可以使用集跟踪已存储的标签: var leadNamesForAutoc
var leadNamesForAutocomplete=[];
$('#filterByNameAutosuggestion option').each(function () {
leadNamesForAutocomplete.push({label: $(this).text(), value: $(this).val()});
});
如何将LeadNames推送到仅自动完成唯一标签?您可以使用
集
跟踪已存储的标签:
var leadNamesForAutocomplete=[];
变量标签=新集合();
$(“#filterByNameAutosuggestion选项”)。每个(函数(){
var label=$(this.text();
如果(!labels.has(label)){
标签。添加(标签);
leadNamesForAutocomplete.push({label:label,value:$(this.val()});
}
});
对于唯一标签,您需要检查是否已推送相同的标签
var leadNamesForAutocomplete=[];
var labels = []; // Makes things easier
$('#filterByNameAutosuggestion option').each(function () {
var label = $(this).text(), value = $(this).val();
if (!labels.includes(label)) {
leadNamesForAutocomplete.push({label: label, value: value});
labels.push(label);
}
});
您可以使用.map()
和.indexOf()
如下所示:
var leadNamesForAutocomplete=[];
$('#filterByNameAutosuggestion option').each(function () {
if( loadNamesForAutocomplete.map(o => o.label).indexOf( $(this).text() ) === -1 ) {
leadNamesForAutocomplete.push({label: $(this).text(), value: $(this).val()});
}
});
推送所有对象然后执行重复数据消除,或者在推送之前使用
filter()
检查对象数组中是否存在任何属性值。如果您进行研究,这两种方法都已在本网站上介绍过。