Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Given a json string like this:

[{"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.

Also, in order to check for existing object, does the string need to be parsed into a json object collection?

I tried this:

$.map(val, function (obj) {
    if (obj === val)
        alert('in');
    return obj; // or return obj.name, whatever.
});
like image 693
ShaneKm Avatar asked Feb 28 '13 08:02

ShaneKm


3 Answers

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/

like image 191
Manatok Avatar answered Nov 14 '22 23:11

Manatok


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 ).

Alternatively, you can extend the above code to use arbitrary values to check against.

like image 31
Nick Andriopoulos Avatar answered Nov 14 '22 22:11

Nick Andriopoulos


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
like image 24
Vadim Avatar answered Nov 15 '22 00:11

Vadim