2

I want to achieve the functionality of:

Iterate over the array in the object where k1's value is woo hoo!.

The following works but i'm not sure it's the best way because I think it would need to loop over each object before it found a match.

Array

myArray = [{"k1": "woo hoo!", "k2": ["k2_1","k2_2","k2_3"], "k3": ["k3_v1"]},{"k1": "boo", "k2": ["k2_v1"], "k3": ["k3_v1"]}]

jQuery

$.each(myArray, function (obj, v) {
    $.each(v.k2, function (i, value) {
        if (v.k1 == "woo hoo!") {
            alert(value);
        }
    });
});

The following contains this example as well as a few other commented out examples I have used to understand $.each more.

http://jsfiddle.net/rwone/MnASV/5/

1

1 Answer 1

4

The only change you have to do is to move teh if condition out of the second loop.

In your case the k1 belongs to the outer object, but you are iterating through the second loop even of the value is not matching that can be avoided by checking it before.

// iterate over array within each object
$.each(myArray_1, function (obj, v) {
    if (v.k1 == "woo hoo!") {
        $.each(v.k2, function (i, value) {
            console.log(value);
        });
    }
});

Demo: Fiddle

Sign up to request clarification or add additional context in comments.

4 Comments

If there were many objects in the top level array, it seems it would need to iterate over each one and then perform the actions associated with the matching if condition. I was wondering if there was a quicker and more direct way to define at the top level "only iterate over an object with this certain property?". So something like iterate over this where foo == bar?
Your response has gotten several upvotes whilst I was writing my comment so I am guessing not, thanks for the answer - can accept in 3 minutes.
@user1063287 AFAIK there is no property like that... you can look at Array.filter() even that iterates through each element to find whether it satisfies the condition
@user1063287 don't always trust the upvotes!!! or for the matter downvotes... there could be another solution that I'm not aware of....

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.