vector
vector

Reputation: 7566

javascript - get Object based on property's value

... if I have the following constructor and then create an instance of the class:

    /* Gallery */
function Gallery( _horseName ){
    this.horseName = _horseName
    this.pixList = new Array();
}

var touchGallery = new Gallery( "touch" )

... how can I get the Gallery object based on the value of horseName?

Thought about implementing something like:

Gallery.prototype.getGalleryByHorseName = function( _horseName ){ /* to be implemented */}

... but got stuck on that. Is there a cleaner or canonical way to accomplish this? Eventually I'll have to access that Gallery object in jQuery as well.

Thanks in advance

Upvotes: 1

Views: 2461

Answers (5)

Shedokan
Shedokan

Reputation: 1202

You could go at it by creating an object filled with horse name galleries that havve been created:

/* Gallery */
function Gallery( _horseName ){
    this.horseName = _horseName
    this.pixList = new Array();
    Gallery.galleryList[_horseName] = this; // Add this gallery to the list
}
Gallery.galleryList = {};

var touchGallery = new Gallery( "touch" )
var galleryByName = Gallery.galleryList["touch"];

Upvotes: -1

FishBasketGordo
FishBasketGordo

Reputation: 23132

You could do something like this. I think it's fairly clean and canonical:

var Galleries = (function() {
    var all = [],
        galleriesObj = {};

    galleriesObj.create = function(horseName) {
        var gallery = {
            horseName: horseName,
            pixList: []
        };
        all.push(gallery);
        return gallery;
    };

    galleriesObj.find = function(horseName) {
        var ii;
        for (ii = 0; ii < all.length; ii += 1) {
            if (all[ii].horseName === horseName) {
                return all[ii];
            }
        }
        return null;
    };

    return galleriesObj;
}());

var touchGallery = Galleries.create('touch');

var foundGallery = Galleries.find('touch');

Upvotes: 2

das_weezul
das_weezul

Reputation: 6142

You could do it in a nice oo way, by writing a class which holds a list to all Gallery instances and then write a function iterating over each Gallery object and returning the one with the matching name.

Supaweu shows a very nice and easy (non-oo) example

Upvotes: 1

supaweu
supaweu

Reputation: 64

Simplest solution is to keep your created objects in an object.

var myGalleries = {};

myGalleries['touchA'] = new Gallery( "touchA" );
myGalleries['touchB'] = new Gallery( "touchB" );

Then you can quickly access them by passing a key.

var galleryOfTouchB = myGalleries['touchB'];

Upvotes: 4

jszpila
jszpila

Reputation: 706

You're missing a step or two. You need an array of Gallery objects, and then iterate through the array while checking the _horseName property.

Upvotes: 0

Related Questions