John the Painter
John the Painter

Reputation: 2615

JS making a forEach match more efficient

variants is an object of objects and selectedOptions is an object of option1, option2, option3. The below forEach searches through the variants to find a match.

Is there a more efficient way, using an array method or similar, to do the following:

Object.values(variants).forEach(variant => {
    if (variant.options.option1 === selectedOptions.option1 && variant.options.option2 === selectedOptions.option2 && variant.options.option3 === selectedOptions.option3) {
        selectedVariant = variant.gid;
    }
});

Upvotes: 0

Views: 49

Answers (1)

mcv
mcv

Reputation: 4429

One thing you're doing here is loop through all the variants, overwriting selectedVariant each time you find a match. And if there's supposed to be only one match, you still visit all the other variants when there's no need for it anymore.

More efficient would be:

selectedVariant = Object.values(variants).find(variant => (
    variant.options.option1 === selectedOptions.option1 && 
    variant.options.option2 === selectedOptions.option2 &&
    variant.options.option3 === selectedOptions.option3
)).gid;

That way you stop the moment you find a match.

And to be perfectly honest, setting a variant equal to another variant's gid looks wrong. Either name the variable you assign to selectedVariantGid, or assign the entire variant, and later use the .gid property once you need it. Clear naming is important.

Upvotes: 2

Related Questions