簡體   English   中英

如何檢查對象中的字符串是否在數組中是唯一的

[英]How to check if string within object is unique in array

我有一個字符串 數組

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>"); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM