如何检查对象中的字符串在数组中是否唯一

How to check if string within object is unique in array

我有一个 array of strings:

var arr = [
    {str: 'abc'},
    {str: 'def'},
    {str: 'abc'},
    {str: 'ghi'},
    {str: 'abc'},
    {str: 'def'},
];

我正在寻找一种聪明的方法来将布尔属性unique添加到对象是否str 是独一无二的:

var arr = [
    {str: 'abc', unique: false},
    {str: 'def', unique: false},
    {str: 'abc', unique: false},
    {str: 'ghi', unique: true},
    {str: 'abc', unique: false},
    {str: 'def', unique: false},
];

我的解决方案包含三个 _.each() 循环,看起来很糟糕...首选 lodash 的解决方案。

您可以使用where 来过滤对象。然后你就可以知道你的字符串在对象中是否是唯一的。

_.each(arr, function(value, key) {
    arr[key] = {
        str : value.str,
        unique : _.where(arr, { str : value.str }).length == 1 ? true : false
    };
});

也许更好的版本带有 map :

arr = _.map(arr, function(value) {
    return {
        str : value.str,
        unique : _.where(arr, { str : value.str }).length == 1 ? true : false
    };
});

你不需要任何库,vanilla js 可以工作:

var map = [];
var arr = [
    {str: 'abc'},
    {str: 'def'},
    {str: 'abc'},
    {str: 'ghi'},
    {str: 'abc'},
    {str: 'def'},
];
  
arr.forEach(function(obj) {
    if (map.indexOf(obj.str) < 0) {
      map.push(obj.str);
      obj.unique = true;
      return;
    }
    arr.forEach(function(o) {
      if (o.str === obj.str) o.unique = false;
    });
});

document.write("<pre>");  
document.write(JSON.stringify(arr, null, "  "));
document.write("</pre>");