This question already has answers here:
Object comparison in JavaScript [duplicate]
(10 answers)
Closed 9 years ago.
For convenience I wrote a simple toJSON prototype, for handling JSON that I know to be safe:
String.prototype.toJSON = function () {
return JSON.parse(this.valueOf());
};
I am using it in testing my web-services. Unfortunately even with this simple test:
var v0 = '{"echo":"hello_world"}'.toJSON(), v1 = {"echo": "hello_world"};
It fails:
console.log(v0 == v1); // false
console.log(v0 === v1); // false
console.log(v0.echo == v1.echo); // true
console.log(v0.echo === v1.echo); // true
What do I not know about JavaScript which is causing this issue?
Just because you have the same content, that does not mean that you have the same object instance.
If you had done v1 = v0 instead of initializing v1 seperatly the first two would have returned true.
Update: If you need to compare the two instances to find if they have equal content then you need to define a function which compares each member.
An object in JavaScript, just like everything else except primitives(int, string, Boolean) is a reference.
Having 2 different duplicate objects, means having 2 different references that point to different places within the hype.
You can implement something as simple as that, to basically iterate over all of the primitive properties of an object, and compare them one by one:
Object.prototype.equals = function(x)
{
for(p in this)
{
switch(typeof(this[p]))
{
case 'object':
if (!this[p].equals(x[p])) { return false }; break;
case 'function':
if (typeof(x[p])=='undefined' || (p != 'equals' && this[p].toString() != x[p].toString())) { return false; }; break;
default:
if (this[p] != x[p]) { return false; }
}
}
for(p in x)
{
if(typeof(this[p])=='undefined') {return false;}
}
return true;
}
For two objects to be == they must be the same instance. v0 and v1 are two different instances. If you want to do a deep comparison of objects you can use something like underscore's isEqual method: http://underscorejs.org/#isEqual
_.isEqual(v0, v1);
Related
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do you determine equality for two JavaScript objects?
Object comparison in JavaScript
If I have two arrays or objects and want to compare them, such as
object1 = [
{ shoes:
[ 'loafer', 'penny' ]
},
{ beers:
[ 'budweiser', 'busch' ]
}
]
object2 = [
{ shoes:
[ 'loafer', 'penny' ]
},
{ beers:
[ 'budweiser', 'busch' ]
}
]
object1 == object2 // false
this can be annoying if you're getting a response from a server and trying to see if it's changed
Update:
In response to the comments and worries surrounding the original suggestion (comparing 2 JSON strings), you could use this function:
function compareObjects(o, p)
{
var i,
keysO = Object.keys(o).sort(),
keysP = Object.keys(p).sort();
if (keysO.length !== keysP.length)
return false;//not the same nr of keys
if (keysO.join('') !== keysP.join(''))
return false;//different keys
for (i=0;i<keysO.length;++i)
{
if (o[keysO[i]] instanceof Array)
{
if (!(p[keysO[i]] instanceof Array))
return false;
//if (compareObjects(o[keysO[i]], p[keysO[i]] === false) return false
//would work, too, and perhaps is a better fit, still, this is easy, too
if (p[keysO[i]].sort().join('') !== o[keysO[i]].sort().join(''))
return false;
}
else if (o[keysO[i]] instanceof Date)
{
if (!(p[keysO[i]] instanceof Date))
return false;
if ((''+o[keysO[i]]) !== (''+p[keysO[i]]))
return false;
}
else if (o[keysO[i]] instanceof Function)
{
if (!(p[keysO[i]] instanceof Function))
return false;
//ignore functions, or check them regardless?
}
else if (o[keysO[i]] instanceof Object)
{
if (!(p[keysO[i]] instanceof Object))
return false;
if (o[keysO[i]] === o)
{//self reference?
if (p[keysO[i]] !== p)
return false;
}
else if (compareObjects(o[keysO[i]], p[keysO[i]]) === false)
return false;//WARNING: does not deal with circular refs other than ^^
}
if (o[keysO[i]] !== p[keysO[i]])//change !== to != for loose comparison
return false;//not the same value
}
return true;
}
But in many cases, it needn't be that difficult IMO:
JSON.stringify(object1) === JSON.stringify(object2);
If the stringified objects are the same, their values are alike.
For completeness' sake: JSON simply ignores functions (well, removes them all together). It's meant to represent Data, not functionality.
Attempting to compare 2 objects that contain only functions will result in true:
JSON.stringify({foo: function(){return 1;}}) === JSON.stringify({foo: function(){ return -1;}});
//evaulutes to:
'{}' === '{}'
//is true, of course
For deep-comparison of objects/functions, you'll have to turn to libs or write your own function, and overcome the fact that JS objects are all references, so when comparing o1 === ob2 it'll only return true if both variables point to the same object...
As #a-j pointed out in the comment:
JSON.stringify({a: 1, b: 2}) === JSON.stringify({b: 2, a: 1});
is false, as both stringify calls yield "{"a":1,"b":2}" and "{"b":2,"a":1}" respectively. As to why this is, you need to understand the internals of chrome's V8 engine. I'm not an expert, and without going into too much detail, here's what it boils down to:
Each object that is created, and each time it is modified, V8 creates a new hidden C++ class (sort of). If object X has a property a, and another object has the same property, both these JS objects will reference a hidden class that inherits from a shared hidden class that defines this property a. If two objects all share the same basic properties, then they will all reference the same hidden classes, and JSON.stringify will work exactly the same on both objects. That's a given (More details on V8's internals here, if you're interested).
However, in the example pointed out by a-j, both objects are stringified differently. How come? Well, put simply, these objects never exist at the same time:
JSON.stringify({a: 1, b: 2})
This is a function call, an expression that needs to be resolved to the resulting value before it can be compared to the right-hand operand. The second object literal isn't on the table yet.
The object is stringified, and the exoression is resolved to a string constant. The object literal isn't being referenced anywhere and is flagged for garbage collection.
After this, the right hand operand (the JSON.stringify({b: 2, a: 1}) expression) gets the same treatment.
All fine and dandy, but what also needs to be taken into consideration is that JS engines now are far more sophisticated than they used to be. Again, I'm no V8 expert, but I think its plausible that a-j's snippet is being heavily optimized, in that the code is optimized to:
"{"b":2,"a":1}" === "{"a":1,"b":2}"
Essentially omitting the JSON.stringify calls all together, and just adding quotes in the right places. That is, after all, a lot more efficient.
As an underscore mixin:
in coffee-script:
_.mixin deepEquals: (ar1, ar2) ->
# typeofs should match
return false unless (_.isArray(ar1) and _.isArray(ar2)) or (_.isObject(ar1) and _.isObject(ar2))
#lengths should match
return false if ar1.length != ar2.length
still_matches = true
_fail = -> still_matches = false
_.each ar1, (prop1, n) =>
prop2 = ar2[n]
return if prop1 == prop2
_fail() unless _.deepEquals prop1, prop2
return still_matches
And in javascript:
_.mixin({
deepEquals: function(ar1, ar2) {
var still_matches, _fail,
_this = this;
if (!((_.isArray(ar1) && _.isArray(ar2)) || (_.isObject(ar1) && _.isObject(ar2)))) {
return false;
}
if (ar1.length !== ar2.length) {
return false;
}
still_matches = true;
_fail = function() {
still_matches = false;
};
_.each(ar1, function(prop1, n) {
var prop2;
prop2 = ar2[n];
if (prop1 !== prop2 && !_.deepEquals(prop1, prop2)) {
_fail();
}
});
return still_matches;
}
});
This question already has answers here:
How do I check if an array includes a value in JavaScript?
(60 answers)
Closed 6 years ago.
Is there an easier way to determine if a variable is equal to a range of values, such as:
if x === 5 || 6
rather than something obtuse like:
if x === 5 || x === 6
?
You can stash your values inside an array and check whether the variable exists in the array by using [].indexOf:
if([5, 6].indexOf(x) > -1) {
// ...
}
If -1 is returned then the variable doesn't exist in the array.
Depends on what sort of test you're performing. If you've got static strings, this is very easy to check via regular expressions:
if (/^[56ab]$/.test(item)) {
//-or-
if (/^(foo|bar|baz|fizz|buzz)$/.test(item)) {
doStuff();
} else {
doOtherStuff();
}
If you've got a small set of values (string or number), you can use a switch:
switch (item) {
case 1:
case 2:
case 3:
doStuff();
break;
default:
doOtherStuff();
break;
}
If you've got a long list of values, you should probably use an array with ~arr.indexOf(item), or arr.contains(item):
vals = [1,3,18,3902,...];
if (~vals.indexOf(item)) {
doStuff();
} else {
doOtherStuff();
}
Unfortunately Array.prototype.indexOf isn't supported in some browsers. Fortunately a polyfill is available. If you're going through the trouble of polyfilling Array.prototype.indexOf, you might as well add Array.prototype.contains.
Depending on how you're associating data, you could store a dynamic list of strings within an object as a map to other relevant information:
var map = {
foo: bar,
fizz: buzz
}
if (item in map) {
//-or-
if (map.hasOwnProperty(item)) {
doStuff(map[item]);
} else {
doOtherStuff();
}
in will check the entire prototype chain while Object.prototype.hasOwnProperty will only check the object, so be aware that they are different.
It's perfectly fine. If you have a longer list of values, perhaps you can use the following instead:
if ([5,6,7,8].indexOf(x) > -1) {
}
Yes. You can use your own function. This example uses .some:
var foo = [ 5, 6 ].some(function(val) {
return val === x;
});
foo; // true
This is what I've decided to use:
Object.prototype.isin = function() {
for(var i = arguments.length; i--;) {
var a = arguments[i];
if(a.constructor === Array) {
for(var j = a.length; j--;)
if(a[j] == this) return true;
}
else if(a == this) return true;
}
return false;
}
You would use it like this:
var fav = 'pear',
fruit = ['apple', 'banana', 'orange', 'pear'],
plu = [4152, 4231, 3030, 4409];
if (fav.isin(fruit, plu, 'eggs', 'cheese')) {
//do something cool
}
The advantages are:
it works in IE < 9;
it reads naturally from left to right;
you can feed it arrays or separate values.
If you don't want to allow type coercion (indexOf does not), change the two == to ===. As it stands:
fav = "4231";
plu.indexOf(fav) //-1
fav.isin(plu) //true
no, there might be a few tricks that are case specific but in general i write code like this:
if (someVariable === 1 ||
someVariable === 2 ||
someVariable === 7 ||
someVariable === 12 ||
someVariable === 14 ||
someVariable === 19) {
doStuff();
moreStuff();
} else {
differentStuff();
}
The simple answer is no. You can use a switch statement, which is easier to read if you are comparing a lot of string values, but using it for two values wouldn't look any better.
[Edit] this seems to work, but as Dan pointed out, it is actually a false positive. Do not use this method. I leave it here for educational purposes.
Easiest way I know :
a = [1,2,3,4,5];
if(3 in a) alert("true"); // will alert true
Tested in Chrome console. Not sure if it works in other browsers.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I test for an empty Javascript object from JSON?
var test= {};
var incidentReport = {
"place1": "n/a",
"place2": "n/a",
"place3": "n/a",
}
Above are the two ways my varible is going to look. Ive tryed doing the following code to test if its empty/looks like {}
if(test == "")
and tried
if(test == null)
also tried
if(!test)
Does anyone know where I am going wrong? Just a beginner to JavaScript and JSON. Is what I am doing considered back practice are there better ways to declare this empty?
Thanks for the support
Use JSON.stringify
var test= {};
if(JSON.stringify(test).length==2)
alert('null')
if(test == "")
checks if it is an empty string, so this won't work
if(test == null)
checks if it is null which is "similar" to undefined - this isn't the case
if(!test)
checks if it is a falsy value, this in not the case either.
You have to check if there exist child-elements (properties):
function isEmpty(obj) {
for(var prop in obj) {
if(obj.hasOwnProperty(prop)) return false;
}
return true;
}
if ( isEmpty(test) ){...}
The very important point is the .hasOwnProperty() - this checks if it is a real property of the object and not only inherited through the prototype chain.
test here is an object. so you have to check if there are any prioperties/elements int his object. You can try something like below
var test= {};
function isEmptyObject(obj) {
// This works for arrays too.
for(var name in obj) {
return false
}
return true
}
alert("is this object empty?" + isEmptyObject(test));
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
javascript test for existence of nested object key
I'm attempting to construct an error message for a formset by testing if a certain object is not undefined, and if it's not undefined, then I end up populating it with that error message. The main problem is that I have to validate if each nested object is undefined, which results in some pretty ugly code. Here's the example:
errorsForField: function(fieldName, formsetName, formNumber) {
if (typeof this.model.errors != 'undefined'){
var fieldError = document.createElement('span');
$(fieldError).addClass('field-error');
// THE FOLLOWING LINE THROWS ERROR.
if (formsetName && _.isUndefined(this.model.errors[formsetName][fieldName]) != true) {
$(fieldError).text(this.model.errors[formsetname][fieldName]);
} else if (typeof this.model.errors[fieldName] != "undefined"){
$(fieldError).text(this.model.errors[fieldName]);
}
this.errors[fieldName] = fieldError.outerHTML;
return fieldError.outerHTML;
}
return false;
},
I get an error stating that I cannot determine [fieldName] of an undefined object this.model.errors[formsetName]. In other words, I have to first determine if this.model.errors[formsetName] is empty and then test if [fieldname] is undefined.
This seems like a really cumbersome solution. Any suggestions for changing this?
You can create a library function that takes property names as parameters and returns the final value if it exists, or null:
function TryGetPropertyValue(o, propertyName1 /*, ... propertyNameN */) {
var names = [].slice.call(arguments, 1);
while (o && names.length) {
o = o[names.shift()];
}
return names.length ? null : o;
}
Call it like:
var err = TryGetPropertyValue(this.model.errors, formsetName, fieldName) ||
TryGetPropertyValue(this.model.errors, fieldName);
if (err != null) {
$(fieldError).text(err);
}
If you want it to return undefined instead of null if the field is not found, you can change the function slightly:
function TryGetPropertyValue(o, propertyName1 /*, ... propertyNameN */) {
var names = [].slice.call(arguments, 1);
while (o && names.length) {
o = o[names.shift()];
}
if (names.length == 0) {
return o;
}
}
http://jsfiddle.net/HbggQ/
As Paul suggested, this is an inherent limitation of Javascript. Even Coffeescript (which is just a layer of syntactic sugar on top of JS) doesn't really solve the problem; it just hides the workaround under it's syntactic sugar (which admittedly is really handy)
If you want to stick to Javascript, you basically have two options: use ternary operators, or use boolean operators. Here's examples of each that check A.B.C.D (where A, B, C or D might not exist):
// Returns A.B.C.D, if it exists; otherwise returns false (via ternary)
return !A ? false :
!A.B ? false :
!A.B.C ? false :
A.B.C.D ? A.B.C.D : false;
// Returns A.B.C.D, if it exists; otherwise returns false (via booleans)
return A && A.B && A.B.C && A.B.C.D;
Obviously the latter is a lot shorter. Both solutions rely on Javascript's "truthiness" (ie. that the values 0, "", null, and undefined count as false). This should be fine for your case, as none of those values will have an errors property. However, if you did need to distinguish between (say) 0 and undefined, you could use the ternary style, and replace !A with typeof(A) == 'undefined'.
Let's say I have two objects that only have primitives as properties for members (e.g. the object has no functions or object members):
var foo = {
start: 9,
end: 11
};
var bar = {
start: 9,
end: 11
};
Given two objects like this, I want to know if all their members have the same values.
Right now I'm simpling doing:
if (foo.start === bar.start && foo.end == bar.end) {
// same member values
}
But I'm going to have to work with objects that may have dozens of these primitive members.
Is there anything built into JavaScript to easily allow me to compare them? What's the easiest way to compare all their values?
If both objects are Objects (e.g., created via literal notation [{}] or new Object, not by [say] new Date), you can do it like this:
function primativelyEqual(a, b) {
var name;
for (name in a) {
if (!b.hasOwnProperty(name) || b[name] !== a[name]) {
// `b` doesn't have it or it's not the same
return false;
}
}
for (name in b) {
if (!a.hasOwnProperty(name)) {
// `a` doesn't have it
return false;
}
}
// All properties in both objects are present in the other,
// and have the same value down to the type
return true;
}
for..in iterates over the names of the properties of an object. hasOwnProperty tells you whether the instance itself (as opposed to a member of its prototype chain) has that property. !== checks for any inequality between two values without doing any type coercion. By looping through the names of the properties of both objects, you know that they have the same number of entries.
You can shortcut this a bit if the implementation has the new Object.keys feature from ECMAScript5:
function primativelyEqual(a, b) {
var name, checkedKeys;
checkedKeys = typeof Object.keys === "function";
if (checkedKeys && Object.keys(a).length !== Object.keys(b).length) {
// They don't have the same number of properties
return false;
}
for (name in a) {
if (!b.hasOwnProperty(name) || b[name] !== a[name]) {
// `b` doesn't have it or it's not the same
return false;
}
}
if (!checkedKeys) {
// Couldn't check for equal numbers of keys before
for (name in b) {
if (!a.hasOwnProperty(name)) {
// `a` doesn't have it
return false;
}
}
}
// All properties in both objects are present in the other,
// and have the same value down to the type
return true;
}
Live example
But both versions of the above assume that the objects don't inherit any enumerable properties from their prototypes (hence my opening statement about their being Objects). (I'm also assuming no one's added anything to Object.prototype, which is an insane thing people learned very quickly not to do.)
Definitely possible to refine that more to generalize it, and even make it descend into object properties by the same definition, but within the bounds of what you described (and within the bounds of most reasonable deployments), that should be fine.
You can use a for in loop to loop through every property in an object.
For example:
function areEqual(a, b) {
for (var prop in a)
if (a.hasOwnProperty(prop) && a[prop] !== b[prop])
return false;
return true;
}
Any properties in b but not a will be ignored.
Y'know, something's just occurred to me. Basic object literals are called JSON. The easiest way to compare those two objects is
function equalObjects(obj1, obj2) {
return JSON.stringify(obj1) === JSON.stringify(obj2);
}
If you need to use this in a browser that doesn't have native JSON support, you can use the open source JSON scripts