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.
});
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/
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With