简体   繁体   English

如何基于值而不是键迭代对象数组?

[英]how to iterate over object array based on values, not key?

I know I can iterate over an object array and check values by utilizing the key. 我知道我可以遍历对象数组并通过使用键检查值。 But is there a way to check the key by looking at the value? 但是,有没有一种方法可以通过查看值来检查密钥? I use jQuery although I think this is simply a javascript question. 我使用jQuery,尽管我认为这只是一个JavaScript问题。

var j = [
    {hello : 1},
    {hello : 2},
    {bye : 3}
]


$.each(j, function(i,item){
    if(item.hello==1) alert("hello");
});

How do I make the alert dependent on the value being 1, irrespective of what key it is? 我如何使警报取决于值1,而不管它是什么键?

You would have to iterate through each key in the array, like this: 您将必须遍历数组中的每个键,如下所示:

$.each(j, function(i,item){
    for (var key in item) {
         if (item[key]==1) {
             alert("it said hello");
         }
    }
});

But why not store it in another format, if that's how you'd like to use it? 但是,如果您要使用它,为什么不以其他格式存储它呢? ie,

var j = [
    [hello, 1],
    [hello, 2],
    [bye, 3]
]

There's the for-of loop proposed in ECMAScript 6. ECMAScript 6中提出了for-of循环。

for (item of j){
    if(item.hello==1){
         alert("it said hello");
    }
}

This feature appeared in Firefox 31 and it is shipped with Chrome 38. IE doesn't implement it. 此功能出现在Firefox 31中,并且随Chrome 38一起提供。IE未实现。 Don't know about other browsers. 不了解其他浏览器。

Try 尝试

var j = [
    {hello : 1},
    {hello : 2},
    {bye : 3}
];
$.each(j, function(i, item){;
    $.each(item, function(key, value) {
      if (value === 1) {
        alert("it said hello")
      }
    })
});

For expample: 例如:

var j = [ {hello : 1}, {hello : 2}, {bye : 3} ];
for (var i in j)
{
    for  (var s in j[i])
    {
        if (j[i][s] == 1)
        {
            alert("it said hello");
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM