使用Prototype在javascript中迭代对象的每个属性? [英] Iterating over every property of an object in javascript using Prototype?
问题描述
有没有办法使用Prototype JavaScript框架迭代对象的每个属性?
Is there a way to iterate over every property of an object using the Prototype JavaScript framework?
以下是这种情况:我在JSON中获得了一个AJAX响应类似这样的事情:
Here's the situation: I am getting an AJAX response in JSON that looks something like this:
{foo: 1, bar: 2, barobj: {75: true, 76: false, 85: true}}
如果我将json响应评估为变量 response
,我希望能够遍历 response.barobj
对象中的每个属性,以查看哪些索引为true,哪些索引为false。
If I evaluate that json response in to a variable response
, I want to be able to iterate over each property in the response.barobj
object to see which indexes are true and which are false.
Prototype同时具有 Object.keys()
和 Object.values()
但奇怪的是似乎没有一个简单的 Object.each()
函数!当我迭代一个时,我可以获取Object.keys()和Object.values()的结果并交叉引用另一个,但这是一个黑客,我相信有一个正确的方法来做到这一点!
Prototype has both Object.keys()
and Object.values()
but oddly seems to not have a simple Object.each()
function! I could take the results of Object.keys() and Object.values() and cross-reference the other as I iterate through one, but that is such a hack that I am sure there is a proper way to do it!
推荐答案
你必须先将对象文字转换为原型哈希:
// Store your object literal
var obj = {foo: 1, bar: 2, barobj: {75: true, 76: false, 85: true}}
// Iterate like so. The $H() construct creates a prototype-extended Hash.
$H(obj).each(function(pair){
alert(pair.key);
alert(pair.value);
});
这篇关于使用Prototype在javascript中迭代对象的每个属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!