Question

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
};
Was it helpful?

Solution

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 .

OTHER TIPS

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top