jQuery 对对象进行递归迭代

发布于 2024-08-19 23:51:02 字数 749 浏览 2 评论 0原文

有一天,我以为我在 jQuery 中看到了一个对象迭代器,它有一个可以设置为递归迭代子对象的标志。我认为它是 jQuery.each() 的一部分,但现在我在文档中没有看到该功能。

jQuery中有没有这样的迭代器可以自动递归?

(我知道如何用 javascript 做到这一点。只是想知道我是否真的看到了我以为我看到的东西。)

非常感谢!

编辑:要明确的是,我正在考虑像 jQuery.each() 这样的实用方法,它将递归地迭代 javascript 对象及其嵌套对象。

在下面的示例中,each() 方法将迭代所有对象,包括 myobj.obj2.key2 中的嵌套对象。

我可以发誓我在 jQuery 文档中看到过一些相关内容,但现在我找不到了。

谢谢。

var myobj = {
    obj1: {key1:'val1', key2:'val2'},
    obj2: {key1:'val1', key2: {nest1:'val1', nest2:'val2', nest3:'val3'}},
    obj3: {key1:'val1', key2:'val2'}
}

$jQuery.each(myobj, function(key,val) {
    // Code to run over each key/val pair
    // Does so recursively to include all nested objects
})

The other day I thought I saw an object iterator in jQuery that had a flag that could be set to recursively iterate over child objects. I thought it was part of jQuery.each(), but now I don't see that capability in the docs.

Is there any such iterator in jQuery that can be automatically recursive?

(I know how to do it in javascript. Just wondering if I actually saw what I thought I saw.)

Thanks much!

EDIT: To be clear, I was thinking of a utility method like jQuery.each() that will iterate recursively over javascript objects and their nested objects.

Given the example below, the each() method would iterate over all objects, including the nested one in myobj.obj2.key2.

I could have sworn that I saw something in jQuery docs about that, but now I can't find it.

Thanks.

var myobj = {
    obj1: {key1:'val1', key2:'val2'},
    obj2: {key1:'val1', key2: {nest1:'val1', nest2:'val2', nest3:'val3'}},
    obj3: {key1:'val1', key2:'val2'}
}

$jQuery.each(myobj, function(key,val) {
    // Code to run over each key/val pair
    // Does so recursively to include all nested objects
})

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

蹲墙角沉默 2024-08-26 23:51:02

.find('selector') 方法基本上是 .children() 的递归版本,它将查找与选择器匹配的任何后代对象,而不是 .children() 只查找第一级后代中的对象。

第二次编辑(我第一次措辞很糟糕,并且把代码弄乱了一点!):

好吧,我不认为这个功能作为一个标志是有意义的:你可以很高兴地永远递归该对象(相信我,我打破了 Firefox 的做法),因此您需要某种交互来确保仅当子对象是有效的递归候选对象时才进行递归。

您需要做的只是像这样拆分函数:

var myobj = {
  obj1: {
    key1: 'val1',
    key2: 'val2'
  },
  obj2: {
    key1: 'val1',
    key2: {
      nest1: 'val1',
      nest2: 'val2',
      nest3: 'val3'
    }
  },
  obj3: {
    key1: 'val1',
    key2: 'val2'
  }
}

$jQuery.each(myobj, function(key, val) {
  recursiveFunction(key, val)
});

function recursiveFunction(key, val) {
  actualFunction(key, val);
  var value = val['key2'];
  if (value instanceof Object) {
    $.each(value, function(key, val) {
      recursiveFunction(key, val)
    });
  }

}

function actualFunction(key, val) {
  /// do stuff
}

The .find('selector') method is basically a recusive version of .children(), and will find any descendant object that matched the selector, as opposed to .children() which only finds objects in the first level of descendants.

2nd EDIT (I phrased badly the first time, and messed up the code a bit!):

Ok, I don't think this functionality as a flag would make sense: you can quite happily recurse through that object forever (believe me, I broke firefox doing it), so you need some sort of interaction to make sure you only recurse when the child object is a valid recursion candidate.

What you need to do is simply split the function like so:

var myobj = {
  obj1: {
    key1: 'val1',
    key2: 'val2'
  },
  obj2: {
    key1: 'val1',
    key2: {
      nest1: 'val1',
      nest2: 'val2',
      nest3: 'val3'
    }
  },
  obj3: {
    key1: 'val1',
    key2: 'val2'
  }
}

$jQuery.each(myobj, function(key, val) {
  recursiveFunction(key, val)
});

function recursiveFunction(key, val) {
  actualFunction(key, val);
  var value = val['key2'];
  if (value instanceof Object) {
    $.each(value, function(key, val) {
      recursiveFunction(key, val)
    });
  }

}

function actualFunction(key, val) {
  /// do stuff
}
彡翼 2024-08-26 23:51:02

上面的 @Ed Woodcock 版本的稍微简化的版本。我需要使用它的方式是输出带有命名链接的 HTML 项目符号列表。

var list = "<ul>";
$.each(data, recurse);

function recurse(key, val) {
    list += "<li>";
    if (val instanceof Object) {
        list += key + "<ul>";
        $.each(val, recurse);
        list += "</ul>";
    } else {
        list += "<a href='" + val + "'>" + key + "</a>";
    }
    list += "</li>";
}
list += "</ul>";

$("#container").html(list);

A slightly simlified version of @Ed Woodcock's version above. They way I needed to use this was to output an HTML bulleted list with named links.

var list = "<ul>";
$.each(data, recurse);

function recurse(key, val) {
    list += "<li>";
    if (val instanceof Object) {
        list += key + "<ul>";
        $.each(val, recurse);
        list += "</ul>";
    } else {
        list += "<a href='" + val + "'>" + key + "</a>";
    }
    list += "</li>";
}
list += "</ul>";

$("#container").html(list);
话少心凉 2024-08-26 23:51:02

你可以更容易地做到这一点

$(this).children().each(function(index, element) {
...
});

you can do this much easier as such

$(this).children().each(function(index, element) {
...
});
上课铃就是安魂曲 2024-08-26 23:51:02

这个问答非常有帮助。谢谢。 (我也很欣赏 cookie 参考资料。我还在努力读完那本书!)。

这是我的版本,对一个简单的 i18n jQuery 解决方案进行“搜索和替换”(这可能对某人有帮助)。如果该术语在字典中,它会发现包装在类中的术语会替换它。

小提琴: http://jsfiddle.net/orolo/CeY5Y/11/

HTML:

In the <span class="i18n">Clear</span> and also <span class="i18n">Save Widget</span>. I'm <span class="i18n">On</span> the <span class="i18n">sub3</span> and <span class="i18n">PDF</span>.

javascript / jQuery:

var term = "";

var customDict = {
    "Level One": {
        "Clear": "1234",
        "CSV": "CSV",
        "First": "First",
        "Last": "Last",
        "Next": "Next",
        "On": "42",
        "Off": "Off",
        "PDF": "alpha",
        "Prev": "Prev",
        "Rows": "Rows",
        "Save Widget": "saver widgetor",
        "Stats": "statistiques",
        "sub": {
            "sub2": {
                "sub3": "inception"
            }
        }
    }
};

function recursiveLookup(key, val) {
    //test for a match between term and key
    if (key === term) {
        $('.i18n').each(function() {
            if ($(this).text() === key) {
              $(this).text(val);  
            }
        });
    }
    //val is an object or no match? recur
    if (val instanceof Object) {
        $.each(val, function(key1, val1) {
            recursiveLookup(key1, val1);
        });
    }
}

function convert() {    
    $('.i18n').each(function(key, val) {
        term = $(this).text();  
        $.each(customDict, function(key, val) {
            recursiveLookup(key, val);
        });

    });
}


/*call the function*/
convert();

This q and a was so helpful. Thank you. (I also appreciated the cookie reference. I'm still slogging through that book!).

Here is my version doing a "search and replace" for a simple i18n jQuery solution (this may be helpful to someone). It finds the term wrapped in a class replaces it if the term is in the dictionary.

Fiddle: http://jsfiddle.net/orolo/CeY5Y/11/

HTML:

In the <span class="i18n">Clear</span> and also <span class="i18n">Save Widget</span>. I'm <span class="i18n">On</span> the <span class="i18n">sub3</span> and <span class="i18n">PDF</span>.

javascript / jQuery:

var term = "";

var customDict = {
    "Level One": {
        "Clear": "1234",
        "CSV": "CSV",
        "First": "First",
        "Last": "Last",
        "Next": "Next",
        "On": "42",
        "Off": "Off",
        "PDF": "alpha",
        "Prev": "Prev",
        "Rows": "Rows",
        "Save Widget": "saver widgetor",
        "Stats": "statistiques",
        "sub": {
            "sub2": {
                "sub3": "inception"
            }
        }
    }
};

function recursiveLookup(key, val) {
    //test for a match between term and key
    if (key === term) {
        $('.i18n').each(function() {
            if ($(this).text() === key) {
              $(this).text(val);  
            }
        });
    }
    //val is an object or no match? recur
    if (val instanceof Object) {
        $.each(val, function(key1, val1) {
            recursiveLookup(key1, val1);
        });
    }
}

function convert() {    
    $('.i18n').each(function(key, val) {
        term = $(this).text();  
        $.each(customDict, function(key, val) {
            recursiveLookup(key, val);
        });

    });
}


/*call the function*/
convert();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文