简体   繁体   English

Jquery或Javascript检查对象是否存在于Json对象的集合中

[英]Jquery or Javascript check if object exists in collection of Json Objects

Given a json string like this: 给出像这样的json字符串:

[{"id":28,"Title":"Sweden"},{"id":56,"Title":"USA"},{"id":89,"Title":"England"}]

I need to check if an object exists, checking all fields, meaning: 我需要检查一个对象是否存在,检查所有字段,意思是:

{"id":28,"Title":"Sweden"} => exists
{"id":29,"Title":"Sweden"} => doesn't exist

OR 要么

{"id":28,"Title":"Sweden"} => exists
{"id":28,"Title":"Sweden2"} => doesn't exist

The collection may have any number of objects and objects will always have an equal number of properties (id, title) or (id, title, firstName) etc. 集合可以包含任意数量的对象,对象将始终具有相同数量的属性(id,title)或(id,title,firstName)等。

Also, in order to check for existing object, does the string need to be parsed into a json object collection? 另外,为了检查现有对象,是否需要将字符串解析为json对象集合?

I tried this: 我试过这个:

$.map(val, function (obj) {
    if (obj === val)
        alert('in');
    return obj; // or return obj.name, whatever.
});

Maybe something like this? 也许是这样的?

    function exists(obj, objs)
    {
        var objStr = JSON.stringify(obj);

        for(var i=0;i<objs.length; i++)
        {
            if(JSON.stringify(objs[i]) == objStr)
            {
                return 1;
            }
        }

        return 0;
    }


    /** some tests **/
    var x = [{"id":28,"Title":"Sweden"},{"id":56,"Title":"USA"},{"id":89,"Title":"England"}];
    var has = {"id":28,"Title":"Sweden"};
    var not = {"id":28,"Title":"Sweden2"};

    /* alerts yes */
    if(exists(has, x)) alert('yes');
    else alert('no');

    /* alerts no */
    if(exists(not, x)) alert('yes');
    else alert('no');

http://jsfiddle.net/zdhyf/ http://jsfiddle.net/zdhyf/

assuming you need a general solution, and not for only the example, you can checkout lodash ( http://lodash.com ) which is a performant library for such operations, and specifically the isEqual function ( http://lodash.com/docs#isEqual ). 假设你需要一个通用的解决方案,而不仅仅是这个例子,你可以检查lodash( http://lodash.com ),它是这种操作的高性能库,特别是isEqual函数( http://lodash.com/) docs#isEqual )。

Alternatively, you can extend the above code to use arbitrary values to check against. 或者,您可以扩展上面的代码以使用任意值进行检查。

If you sure that properties of the objects in collection are always in the same order as in the object you are looking for, you can search for a substring instead of checking presence of the object: 如果您确定集合中对象的属性始终与您要查找的对象的顺序相同,则可以搜索子字符串而不是检查对象的存在:

var json = '[{"id":28,"Title":"Sweden"},{"id":56,"Title":"USA"},{"id":89,"Title":"England"}]',
obj1 = {"id":28,"Title":"Sweden"},
obj2 = {"id":29,"Title":"Sweden"};

alert(json.indexOf(JSON.stringify(obj1)) >= 0 ? 'Yes' : 'No'); // Yes
alert(json.indexOf(JSON.stringify(obj2)) >= 0 ? 'Yes' : 'No'); // No

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM