Tiffany Rehsif
Tiffany Rehsif

Reputation: 33

AS3 accessing object attributes

I'm trying to figure out if there is a way to store objects in an array type data structure, and then later be able to search all of the objects for a specific attribute.

Like, if I have four objects stored in an array (their names are object1-4), and they all have an attribute of ID (object1.ID = 1, object2.ID = 2, object3.ID = 3 , object4.ID = 4) , is there a way to search through all of the objects (object1-4) of the array to find an object ID that matches a number?

for example, if i have my array with [object1, object2, object3, object4] and they all have the ID attribute (object1.ID = 1, object2.ID = 2, object3.ID = 3 , object4.ID = 4) I am trying to find a way to loop through all of the objects to find which one has an ID of 2

var objectList:Array = new Array;
objectList[0] = object1;
objectList[1] = object2;
objectList[2] = object3;
objectList[3] = object4;

function searchArray(searchTerm:int)
{
    if(var i:int = 0; i <  objectList.length ; i++)
    {
       if(objectList[i].ID == searchTerm)
       {  
          trace("Match Found")
       }
    }
}

Upvotes: 0

Views: 493

Answers (2)

Scrimothy
Scrimothy

Reputation: 2536

If your ID = object2 and your searchterm is 2, you'll never match with ==. Try either:

if (Number(objectList[i].ID.replace('object', '')) == searchterm) { ... }

or

if (objectList[i].ID == 'object' + searchterm) { ... }

Upvotes: 0

Alex
Alex

Reputation: 907

    function searchArray(searchTerm:int,searchBy:String = 'ID'):*
    {
        var res:* = null;
        for(var i:int = 0; i <  objectList.length ; i++)
        {
            if(objectList[i].hasOwnProperty(searchBy))
            {
                if(objectList[i][searchBy] == searchTerm)
                {  
                    res = objectList[i];
                    break;
                }
            }

        }
        return res;
    }

Upvotes: 1

Related Questions