我需要通过id
在由某些JSON数据创建的变量中检索对象。
目前我正在使用以下脚本,使用for .. in
查看每个对象的每个属性进行搜索。
我想知道:
id
的对象?http://jsbin.com/jebukameci/1/
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<script>
var data = {
id: 0,
cnt: [
{
id: 1,
cnt: [
{
id: 2,
cnt: [
{
id: 3,
cnt:[]
}
]
}
]
},
]
};
function getById (id) {
function getByIdInner(obj, id) {
var result;
for (var p in obj) {
if (obj.id == id) {
return obj;
} else {
if (typeof obj[p] === 'object') {
result = getByIdInner(obj[p], id);
if (result) {
return result;
}
}
}
}
return result;
}
return getByIdInner(this.data, id);
}
</script>
</head>
<body onload="(function(){console.log(getById(3))})();">
</body>
</html>