我有一个数组,其中包含一些具有相同“id”属性的对象,如下所示:

var regions = [
  {'id': 1, 'value': 'Ankara'},
  {'id': 2, 'value': 'İstanbul'},
  {'id': 2, 'value': 'Istanbul'}
]

如果重复,我尝试仅显示特定ID的第一个对象(在这种情况下,我想显示“İstanbul”,而不是“Istanbul”)。
我试图在source属性中使用一个函数,但是失败了,我不确定要在哪里执行此操作……这是一个代码段:

var regions = [
	{'id': 1, 'value': 'Ankara'},
	{'id': 2, 'value': 'İstanbul'},
	{'id': 2, 'value': 'Istanbul'}
]

$('#myInput').autocomplete({
	source: regions
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<input type="text" placeholder="type here ..." id="myInput">


任何帮助将不胜感激。谢谢。

最佳答案

这可能是您的解决方案。我创建了一个函数,该函数将根据属性从数组中删除重复项。函数会将唯一的对象添加到uniqueArray,所有具有相同ID的所有下一个项目都将被忽略。

之后,我将uniqueArray传递给jQuery autocomplete。

请记住,Array.reduce可在IE9 +上运行

随时询问您是否有任何问题。

var regions = [
	{'id': 1, 'value': 'Ankara'},
	{'id': 2, 'value': 'İstanbul'},
	{'id': 2, 'value': 'Istanbul'}
]

var uniqueRegions = removeDuplicates(regions, 'id')

function removeDuplicates(arr, field) {
    var u = [];
    arr.reduce(function (a, b) {
        if (a[field] !== b[field]) {
            u.push(b);
        }
        return b;
    }, []);
    return u;
}

$('#myInput').autocomplete({
	source: uniqueRegions
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<input type="text" placeholder="type here ..." id="myInput">

10-06 12:42
查看更多