【问题标题】:Search javascript hashmap with another hashmap value用另一个 hashmap 值搜索 javascript hashmap
【发布时间】:2014-03-10 11:40:50
【问题描述】:

我有两个 hashmap,hashmap1 和 hashmap2。每个哈希图都有多个键,每个键都有多个值。

var hashmap1 = {
    a:[
         'aaa',
         'bbb'           
    ]
    b:[
        'ccc',
        'ddd'
    ]
};

var hashmap2 = {
    a:[
         'aaa',
         'bbb',
         'ccc',
    ]
    b:[
        'ddd',
        'eee',
        'fff'
    ]
};

在上面的示例中,我想检查 hashmap1 中每个键的所有值是否存在于 hashmap2 的值中。

所以在上面的例子中,hashmap1 中的所有值都存在于 hashmap2 的值中。如果是这种情况,可以将变量标记为 true,否则将其标记为 false。

感谢您的帮助

【问题讨论】:

    标签: javascript hashmap


    【解决方案1】:

    我刚刚写了一个类似的比较函数。它使用 jquery,我希望它不是问题。

    /**
     * Checks if an object or array is a subset of another object or array.
     * Also works with scalar types.
     *
     * @requires jQuery
     * @param {mixed} partial
     * @param {mixed} whole
     * @param {boolean} strict_arrays In arrays, compare with a[i] === b[i] instead of inArray(a[i], b). Default false.
     * @returns {boolean} 'partial' is a subset of 'whole'
     */
    function is_subset(partial, whole, strict_arrays) {
        if (partial instanceof Array) {
            if (!(whole instanceof Array)) return false;
            var matches = true;
            $.each(partial, function(i, value){
                if ((!strict_arrays && $.inArray(value, whole) < 0) || (strict_arrays && value !== whole[i])) {
                    matches = false;
                    return false;
                }
            });
            return matches;
        } else if (typeof partial === 'object' && partial !== null) {
            if (!(typeof whole === 'object')) return false;
            var matches = true;
            $.each(partial, function(prop, value) {
                if (!is_subset(value, whole[prop])) {
                    matches = false;
                    return false;
                }
            });
            return matches;
        } else {
            return partial === whole;
        }
    }
    

    与您的示例一起使用:is_subset(hashmap1, hashmap2)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-06
      • 2020-04-09
      • 2015-10-21
      相关资源
      最近更新 更多