是否有办法以递归方式循环遍历JS / jQuery对象的所有嵌套属性?
例如,给定此对象
var x = {
'name': 'a',
'level': 1,
'children': [{
'name': 'b',
'level': 2,
'children': [{
'name': 'c',
'level': 3,
'children': [{
...
}]
}]},
...
}]
}
我怎么能无限制地圈出名为'a'的对象及其子女,'b'及其子女,'c'及其子女?
答案 0 :(得分:18)
递归方法似乎最好,类似这样:
function recursiveIteration(object) {
for (var property in object) {
if (object.hasOwnProperty(property)) {
if (typeof object[property] == "object"){
recursiveIteration(object[property]);
}else{
//found a property which is not an object, check for your conditions here
}
}
}
}
答案 1 :(得分:1)
您的JSON格式不正确,但您可以“访问”每个项目,如下所示:
<html>
<head>
<title>test</title>
<script type="text/javascript">
var x = {
"name": "a",
"level": 1,
"children": [
{
"name": "b",
"level": 2,
"children": [
{
"name": "c",
"level": 3,
"children": [
{
"sss": 23
}
]
}
]
}
]
};
function visit(obj){
for(var prop in obj){
if(typeof(obj[prop]) == 'object'){
if(Object.prototype.toString.call(obj[prop]) == '[object Array]'){
for(var i = 0; i < obj[prop].length; i++){
document.write("<br />the element " + prop + " (array) was visited");
visit(obj[prop][i]);
}
}else{
document.write("<br />the element " + prop + " (object) was visited");
visit(obj[prop]);
}
}else{
document.write("<br />the element " + prop + " = " + obj[prop] + " was visited");
}
}
}
visit(x);
</script>
</head>
<body>
</body>
答案 2 :(得分:1)
我最初正在寻找一种递归搜索javascript对象的方法,我发现这篇文章非常有用,尤其是Jeroen Moons的回答。我已经调整它以提供返回对象。输入对象进行搜索,输入 {key:value} 对象(针)。
function searchObject(object, keyvalue){
var found = false;
for (var property in object){
if (object.hasOwnProperty(property)){
if (typeof object[property] == 'object'){
found = searchObject(object[property], keyvalue);
if (found)
return found;
}else{
key = Object.keys(keyvalue)[0];
if (property == key && object[key] == keyvalue[key]){
console.log('searchObject ' + keyvalue[key] + ' found');
return object;
}
}
}
}
}
答案 3 :(得分:0)
var x = {
'name': 'a',
'level': 1,
'children': [{
'name': 'b',
'level' : 2,
'children' : [{
'name': 'c',
'level' : 3,
'children' : [{
}]
}]
}, {
'name': 'b2',
'level' : 2,
'children' : [{
'name': 'c2',
'level' : 3,
'children' : [{
}]
}]
}]
}
var step = x;
do {
if (step instanceof Array){
for (i=0; i < step.length; i++) {
callback(step[i]);
}
}
else {
callback(step);
}
step = step.children != undefined ? step.children : null;
} while (step);
function callback (element) {
console.log(element);
}
只要结构不变,就可以这样下去。
答案 4 :(得分:0)
function iterate(obj){
for(var key in obj)
{
if(typeof(obj["key"]) == "object"){
iterate(obj["key"]);
}
else{
console.log(key + ": " + obj["key"];
}
}
}