如何查看给定对象是否与firebase返回的对象之一匹配

时间:2015-06-14 07:04:23

标签: javascript object firebase

我正在尝试测试给定的object是否与从firebase存储和返回的stored objects匹配。如果是,则返回true或在变量中存储true。

以下是给定对象和firebase返回数据的示例

给定对象:

{name: "John", age: "32"}

存储对象:

{ 
    '-JrYqLGTNLfa1zEkTG5J': { name: "John", age: "32" },
    '-JrkhWMKHhrShX66dSWJ': { name: "Steve", age: "25" },
    '-JrkhtHQPKRpNh0B0LqJ': { name: "Kelly", age: "33" },
    '-JrkiItisvMJZP1fKsS8': { name: "Mike", age: "28" },
    '-JrkiPqA8KyAMj2R7A2h': { name: "Liz", age: "22" } 
}

3 个答案:

答案 0 :(得分:5)

var storedObject ={ 
    '-JrYqLGTNLfa1zEkTG5J': { name: "John", age: "32" },
    '-JrkhWMKHhrShX66dSWJ': { name: "Steve", age: "25" },
    '-JrkhtHQPKRpNh0B0LqJ': { name: "Kelly", age: "33" },
    '-JrkiItisvMJZP1fKsS8': { name: "Mike", age: "28" },
    '-JrkiPqA8KyAMj2R7A2h': { name: "Liz", age: "22" } 
};
var givenObject = {name: "John", age: "32"};

这是检查对象是否相等的方法。你只需要循环对象

Javascript Way

for(key in storedObject){
    if(JSON.stringify(storedObject[key]) === JSON.stringify(givenObject)){
     alert('equal'+givenObject['name'] +givenObject['age']);
    }
};

jQuery Way

使用$.each()函数

$.each(storedObject,function(key,value){
    if(JSON.stringify(value) === JSON.stringify(givenObject)){
     alert('equal'+givenObject['name'] +givenObject['age']);
    }
});

看看FIDDLE LINK 另外,如需了解相关信息,请查看 SO Object comparison in JavaScript LINK

答案 1 :(得分:2)

为了完整性,这里是iOS / MacOS中的解决方案

//query for all users
FQuery *allUsersRef = [usersRef queryOrderedByChild:@"name"];

//filter that query with a query for users named "John"
FQuery *justJohnRef = [allUsersRef queryEqualToValue:@"John"]; 

//read in all of the resulting users named John
[justJohnRef observeSingleEventOfType:FEventTypeValue withBlock:^(FDataSnapshot *snapshot) {

    NSArray *johnArray = [snapshot.value allObjects];

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"age == %@", @"32"];
    NSArray *result = [johnArray filteredArrayUsingPredicate:predicate];

    NSLog(@"%@", result);

}];

这里的概念是我们使用广泛的查询来引入我们需要的一系列数据,在这种情况下,所有名为John的用户,然后在代码中为所有返回的32岁的John用户过滤该数据。

请注意,如果John年龄超过32岁,则结果数组将包含所有这些数据。应该向NSPredicate提供更详细的信息,以获得您正在寻找的确切John(即SSN = x或驾驶执照= y)

答案 2 :(得分:0)

以下是使用可重用代码(需要符合ES5环境)的通用示例,因此它不仅限于您提供的数据。

// some generic reuseable code
(function () {
    'use strict';

    function $isPrimitive(inputArg) {
        var type = typeof inputArg;

        return type === 'undefined' || inputArg === null || type === 'boolean' || type === 'string' || type === 'number' || type === 'symbol';
    }

    function $isFunction(inputArg) {
        return typeof inputArg === 'function';
    }

    function $isDate(inputArg) {
        return Object.prototype.toString.call(inputArg) === '[object Date]';
    }

    function $isRegExp(inputArg) {
        return Object.prototype.toString.call(inputArg) === '[object RegExp]';
    }

    function $isString(inputArg) {
        return Object.prototype.toString.call(inputArg) === '[object String]';
    }

    function $isArguments(inputArg) {
        return Object.prototype.toString.call(inputArg) === '[object Arguments]';
    }

    function $getItem(object, index) {
        var item;

        if ($isString(object)) {
            item = object.charAt(index);
        } else {
            item = object[index];
        }

        return item;
    }

    var de = function (a, b, circ) {
        if (a === b) {
            return true;
        }

        var aType,
            bType,
            aIsArgs,
            bIsArgs,
            aIsPrim,
            bIsPrim,
            aCirc,
            bCirc,
            ka,
            kb,
            length,
            index,
            it;

        if ($isDate(a) && $isDate(b)) {
            return a.getTime() === b.getTime();
        }

        if ($isRegExp(a) && $isRegExp(b)) {
            return a.source === b.source &&
                a.global === b.global &&
                a.multiline === b.multiline &&
                a.lastIndex === b.lastIndex &&
                a.ignoreCase === b.ignoreCase &&
                a.sticky === b.sticky;
        }

        aIsPrim = $isPrimitive(a);
        bIsPrim = $isPrimitive(b);
        if ((aIsPrim || $isFunction(a)) && (bIsPrim || $isFunction(b))) {
            /*jslint eqeq: true */
            return a == b;
        }

        if (aIsPrim || bIsPrim) {
            return a === b;
        }

        if (a.prototype !== b.prototype) {
            return false;
        }

        if (circ.a.indexOf(a) === -1) {
            circ.a.push(a);
        } else {
            aCirc = true;
        }

        if (circ.b.indexOf(b) === -1) {
            circ.b.push(b);
        } else {
            bCirc = true;
        }

        if (aCirc && bCirc) {
            circ.cnt += 1;
        } else {
            circ.cnt = 0;
        }

        if (circ.cnt > 200) {
            throw new RangeError('Circular reference limit exceeded');
        }

        aIsArgs = $isArguments(a);
        bIsArgs = $isArguments(b);
        if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs)) {
            return false;
        }

        if (aIsArgs) {
            return de(Array.prototype.slice.call(a), Array.prototype.slice.call(b), circ);
        }

        ka = Object.keys(a);
        kb = Object.keys(b);
        length = ka.length;
        if (length !== kb.length) {
            if (Array.isArray(a) && Array.isArray(b)) {
                if (a.length !== b.length) {
                    return false;
                }
            } else {
                return false;
            }
        } else {
            ka.sort();
            kb.sort();
            for (index = 0; index < length; index += 1) {
                if (ka[index] !== kb[index]) {
                    return false;
                }
            }
        }

        for (index = 0; index < length; index += 1) {
            it = ka[index];
            if (!de($getItem(a, it), $getItem(b, it), circ)) {
                return false;
            }
        }

        aType = typeof a;
        bType = typeof b;

        return aType === bType;
    };

    if (!Object.prototype.deepEqual) {
        Object.defineProperty(Object.prototype, 'deepEqual', {
            enumerable: false,
            configurable: true,
            writable: true,
            value: function (b) {
                var a = this;
                
                return de(a, b, {
                    a: [],
                    b: [],
                    cnt: 0
                });
            }
        });
    }

    if (!Object.prototype.forKeys) {
        Object.defineProperty(Object.prototype, 'forKeys', {
            enumerable: false,
            configurable: true,
            writable: true,
            value: function (fn, thisArg) {
                var object = Object(this),
                    keys,
                    length,
                    val,
                    index,
                    it;

                if (!$isFunction(fn)) {
                    throw new TypeError('Argument is not a function: ' + fn);
                }

                keys = Object.keys(object);
                length = keys.length;
                val = false;
                for (index = 0; index < length; index += 1) {
                    it = keys[index];
                    val = !!fn.call(thisArg, $getItem(object, it), it, object);
                    if (val) {
                        break;
                    }
                }

                return val;
            }
        });
    }
}());

// example of use with your data
var stored = {
        '-JrYqLGTNLfa1zEkTG5J': {
            name: "John",
            age: "32"
        },
            '-JrkhWMKHhrShX66dSWJ': {
            name: "Steve",
            age: "25"
        },
            '-JrkhtHQPKRpNh0B0LqJ': {
            name: "Kelly",
            age: "33"
        },
            '-JrkiItisvMJZP1fKsS8': {
            name: "Mike",
            age: "28"
        },
            '-JrkiPqA8KyAMj2R7A2h': {
            name: "Liz",
            age: "22"
        }
    },
    given = {
        name: "John",
        age: "32"
    },
    found = stored.forKeys(function (item) {
        return item.deepEqual(this);
    }, given);

document.getElementById('out').textContent = 'given was matched in stored: ' + found;
<pre id="out"></pre>