如何搜索对象数据?

时间:2014-03-15 23:17:42

标签: javascript javascript-objects

我有多个具有x和y值的对象,

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;

您如何确定哪个对象的x和y = 1?

你可以将x和y值传递给函数。

function = function(x,y) {
    // code to find which objects x and y = parameters
};

3 个答案:

答案 0 :(得分:1)

也许" x在y"循环是你正在寻找的。这是你如何做到的:

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);
}

以下是更多信息http://www.ecma-international.org/ecma-262/5.1/#sec-12.6.4

答案 1 :(得分:0)

我会使用以下内容:

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

然后使用findObject(object, 1, 1)会为您提供xy等于1的对象。

请参阅此fiddle

答案 2 :(得分: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)

应该工作得很好,但你应该让这个函数有一个变量' object'所以不是这个硬编码的例子。

相关问题