试试这个简单的递归函数:
find = function(where, what) {
if (typeof where != "object")
return null;
var matches = true;
for (var p in what)
matches = matches && (where[p] == what[p]);
if (matches)
return where;
for (var p in where) {
var found = find(where[p], what);
if(found)
return found;
}
return null;
}
它适用于任何深度的对象,并允许多个搜索键。对于您的示例:
var data = {"data":
[{"obj1":"value1",
"obj2":"value2"},
{"obj1":"value3",
"obj2":"value4"},
{"obj1":"value5",
"obj2":"value6"}]
};
result = find(data, {"obj2":"value4"})
console.log(result.obj1) // value3
另一种(更好的)方法是为 finder 函数提供一个测试谓词:
find = function(where, test) {
if (test(where))
return where;
if (typeof where != "object")
return null;
for (var p in where) {
var found = find(where[p], test);
if (found)
return found;
}
return null;
}
result = find(data, function(x) { return x.obj2 == "value4" });