0

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.

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
  • 2
    You would to iterate through all the keys to find the value you want and then grab the corresponding key. The data is not indexed by value. Commented Oct 22, 2014 at 0:33

4 Answers 4

1

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")
      }
    })
});
Sign up to request clarification or add additional context in comments.

Comments

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]
]

1 Comment

yup. if I knew my data would never change structure i'd do it array-style, but it's not extensible that way. I'm keeping all data in objects so I can store anything I want.
1

There's the for-of loop proposed in ECMAScript 6.

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. Don't know about other browsers.

1 Comment

I like it. But alas, dodgy support atm, so gonna have to wait.
0

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");
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.