使用另一个hashmap值搜索javascript hashmap

时间:2014-03-10 11:40:51

标签: javascript hashmap

我有两个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。

感谢您的帮助

1 个答案:

答案 0 :(得分: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)

相关问题