I have the following function:
function containsObject(object, array) {
for (var i = 0; i < array.length; i++) {
if (array[i] === object) {
return i;
}
}
return false;
}
The following array:
var array = [
{
name: 'test1',
age: 12
},
{
name: 'test2',
age: 14
}
];
And I need to check if the following object is in the array:
var object = {
name: 'test1',
age: 12
};
But when I use the function to check if the array contains the object:
console.log(containsObject(object, array));
It will return false, since the references of the objects aren't the same. So technically speaking, the objects aren't the same.
How do I go on about this without sharing references?
Fiddle : https://jsfiddle.net/thatOneGuy/3ys6s7sy/2/
Youll have to check each element of the object with each element of the other object.
function containsObject(object, array) {
for (var i = 0; i < array.length; i++) {
var count = 0;
var matching = true;
for (var key in object) {
if (array[i][key] === object[key]) {
matching = true;
if (count == Object.keys(array[i]).length - 1 && matching) {
return i;
} else {
count++;
}
} else {
matching = false;
}
}
}
return false;
}
var array = [{
name: 'test2',
age: 14
}, {
name: 'test1',
age: 12
}];
var thisObject = {
name: 'test1',
age: 12
};
console.log(containsObject(thisObject, array));
I changed the data around to see if it works. It now logs 'i' correctly. This would be quite slow if you have a lot of data to compare. You can always stringify the two objects and compare the two strings ?
Here is that function :
function containsObject(object, array) {
for (var i = 0; i < array.length; i++) {
for (var key in object) {
//if (array[i][key] === object[key]) {
// return i;
//}
if (JSON.stringify(array[i]) === JSON.stringify(object)) {
return i;
}
}
}
return false;
}
As mentioned in the comments the first one wouldn't cater for deep comparison. Whereas the stringify would. I would be careful about the objects being in different order though. For example if you use this object :
var thisObject = {
age: 12,
name: 'test1'
};
To compare, it wouldn't work as its just a straight string comparison.
Fiddle with stringify : https://jsfiddle.net/thatOneGuy/3ys6s7sy/1/
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