0

I have multiple objects with x and y values,

var object = new Object();
     object.one = new Object(); 
         object.one.x = 0;
         object.one.y = 0;
     object.two = new Object();
         object.two.x = 1;
         object.two.y = 1;

How would you determine which object has an x and a y that = 1?

You could pass is an x and y value to a function.

function = function(x,y) {
    // code to find which objects x and y = parameters
};
JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
morgan
  • 1
  • 1

3 Answers3

1

Maybe "x in y" loop is what you are looking for. Here is how you do it:

for(var p in object) // String p will be "one", "two", ... all the properties
{
    if(object[p].x == 1 && object[p].y == 1) console.log(p);
}

Here is more info http://www.ecma-international.org/ecma-262/5.1/#sec-12.6.4 .

Ivan Kuckir
  • 2,327
  • 3
  • 27
  • 46
0

I'd use something along the lines of:

var findObject = function(object, x, y) {
    for(var subObject in object) {
        if(object[subObject].x === x && object[subObject].y === y)
            return object[subObject];
    }
};

Then using findObject(object, 1, 1) will give you the object with x and y equal to 1.

See this fiddle.

nickell
  • 389
  • 2
  • 14
0
search = function(x, y) {
    for (var p in object) {
        if (object[p].x == x && object[p].y == y) console.log(p);
    }
}

search(1, 1)

Should work just fine, but you should probably make the function have a variable 'object' so rather than this hardcoded example.

John Karasinski
  • 977
  • 7
  • 16