1

I've got an array of objects defined like this:

var editionsObj = new Array();
function editionObject(name,description)
{
 this.name = name;
 this.description = description;
}

I need to search the editionsObj array for the existence of a variable in the name field. If no object in array has a name value equal to what I need, I'm going to insert it into the array. I've seen some examples in jQuery but wasn't able to get any to work.

Thanks in advance!

asked May 26, 2011 at 19:29

3 Answers 3

1

Was able to solve this with code similar to the following:

var objCheck = null;
objCheck = jQuery.grep(editionsObj, function(n, i) {
 return n.name == currentEdition;
});
if ((objCheck == null) || (objCheck.length == 0))
{
 editionsCount++;
 editionsObj[editionsCount] = new editionObject(currentEdition,currentFamily,'');
}

Basically it performs a grep on the object array checking a certain index (name) for the value. If the value doesn't exist, then I perform the add.

Hope it helps someone else!

answered May 27, 2011 at 11:56
Sign up to request clarification or add additional context in comments.

Comments

0

I'm going to assume that each element of your array has only two properties. If that's correct, then forget the idea of having named properties and just use a JS object:

var editionsObj = {};
function addIfNotExists(name,description){
 if(!(name in editionsObj)) editionsObj[name] = description;
}
answered May 26, 2011 at 19:40

2 Comments

From the context of the variable name convention, it looks like it's possible items with the same "names" will have several "editions." Might need more info to determine if this is a viable solution.
I took If no object in array has a name value equal to what I need, I'm going to insert it into the array to mean that there's only description per name, but I suppose it could be interpreted differently.
0

A simple for loop should suffice:

var nameToSearchFor = 'Bob',
 desc = 'whatever',
 alreadyExists = false;
for (var i = 0, il = editionsObj.length; i < il; i++) {
 if (editionsObj[i].name === nameToSearchFor) {
 alreadyExists = true;
 break;
 }
}
if (!alreadyExists) {
 editionsObj.push(new editionObject(nameToSearchFor, desc));
}
answered May 26, 2011 at 19:40

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.