从对象列表中获取数据的最有效方法是什么?

时间:2012-04-13 22:28:44

标签: javascript

我有一个像这样的对象列表(从PHP创建然后json编码):

{"10":{"10":["4","7","2","2","0","32"],"11":["5","22","1","1","0","0"]}}

translated:

{"X":{"Y":["unique_id","data","data","data","data","data"],"Y":["unique_id","data","data","data","data","data"]

但是我试图通过寻找unique_id来找到获取X:Y的方法让我们说它是4。

最有效的方法是什么?

1 个答案:

答案 0 :(得分:1)

如果它们是唯一的ID,请创建一个单独的查找表。

var id_lookup = {};

for(var x in data)
    for(var y in data[x])
        id_lookup[data[x][y][0]] = [x,y]

var coords = id_lookup[4];

alert(coords);  // [10,10]

alert(data[coords[0]][coords[1]]); // ["4","7","2","2","0","32"]

DEMO: http://jsfiddle.net/LXE3B/