2

Is it possible in JavaScript (Or library JQuery) to find all (global) objects which have a given pattern ?

For example:

objekt_1
objekt_2 //Javascript objects

function find_objects() {
     return ....; //return all objects that start with "object"-prefix
}
Tony
  • 2,266
  • 4
  • 33
  • 54
  • 3
    why would you want to do that?if you create these objects, it makes more sense to put them inside an array. – mpm Mar 31 '14 at 09:50
  • see this http://stackoverflow.com/questions/8409577/get-all-the-objects-dom-or-otherwise-using-javascript – web-nomad Mar 31 '14 at 09:50
  • @mpm Very good consideration. I want it because I'm not controll all the javascript code. – Tony Mar 31 '14 at 09:56

3 Answers3

2

Yes. If they are global, they are stored in window object. Then you just need to filter them:

function find_objects() {
    var objs = [];
    for (var k in window) {
        var cVariable = window[k];
        if (/^objekt/.test(k) && typeof cVariable === "object") {
             objs.push(cVariable);
        }
    }
    return objs;
}

Demo:

> function find_objects() {
    var objs = [];
    for (var k in window) {
        if (/^objekt/.test(k) && typeof window[k] === "object") {
             objs.push(window[k]);
        }
    }
    return objs;
}
undefined
>find_objects()
[]
>var objekt_1 = {a: 1}
undefined
>find_objects()
[Object]

JSBIN

Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474
1

Yes.

Global variables in javascript are actually elements of the window object, so you can do this:

for(var i in window) {
    var ret = [];
    if(i.substr(0,7) == 'object_') ret.push(i);
    return ret;
}
Benubird
  • 18,551
  • 27
  • 90
  • 141
1

As they're globals, they're properties on the global object, which is referenced via the window variable on browsers. So you may be able to find them with a for-in loop:

var key;
for (key in window) {
    // Examine `key` here, it's a string; if it matches, do
    // something with `window[key]`, which is the value for that variable
}
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875