Reputation: 1516
I have tried many things to get this working correctly but I can't
Here is my problem:
I have an array of objects in javascript which looks something like this:
var myArrOfObjs = [];
var myObject1 = {};
myObject1.key = '1234';
myObject1.label = 'Richard Clifford';
myArrOfObjs.push( myObject1 );
and I need to do something like:
if( !containsObject( myObject1, myArrOfOjbs ) ){
// Do stuff
}
I need the containsObject
function to check for key values within the found object (if any), so if containsObject( myObject1, myArrOfOjbs )
finds the object, I need to check to see if the key of that is the same as the one I am currently trying to push.
The reason I need it to check the keys is because I have tried this function which I found else where on StackOverflow, but it isn't quite working.
function containsObject(obj, list) {
var i;
for (i = 0; i < list.length; i++) {
if (list[i] == obj) {
return true;
}
}
return false;
}
It still pushes the object to the array even when it already contains the object.
Please let me know if you need anything clearing up, I realise that it isn't the easiest post to read/understand.
Thanks!
Upvotes: 0
Views: 1392
Reputation: 25322
Maybe it's not the answer you're looking for, but I wonder why don't use an Object instead of an Array, if you have a key:
var objectList = {};
var myObject { key : '1234', label : 'Richard Clifford' };
objectList[myObject.key] = myObject;
So if you want to iterate:
for (var key in objectList) {
if (objectList.hasOwnProperty(key)
alert(key);
}
If you want to access to the object with a key given you have just to:
alert(objectList['1234'].label);
Upvotes: 1
Reputation: 4509
I have got this function that gets added to the prototype-chain of the Array-Object, so you can just call list.hasObject(obj)
.
Array.prototype.hasObject = (
!Array.indexOf ? function (o)
{
var l = this.length + 1;
while (l -= 1)
{
if (this[l - 1] === o)
{
return true;
}
}
return false;
} : function (o)
{
return (this.indexOf(o) !== -1);
}
);
small fiddle for this: http://jsfiddle.net/NE9kx/
Upvotes: 1
Reputation: 838076
You need to change the equality test to compare the keys:
function containsObject(obj, list) {
var i;
for (i = 0; i < list.length; i++) {
if (list[i].key === obj.key) {
return true;
}
}
return false;
}
Upvotes: 3