Karim Ali
Karim Ali

Reputation: 2453

Can my code be made more efficient if I need to update pin based on a condition in javascript?

I have a variable AllPackages which is an array of objects. I want to get all the same Products in all objects in AllPackages and update their pin with the selectedPIN if dp.product.code matches with the object's dealProducts product's code.

setProductPinOnAllPackages(dp): void {
    let AllPackages = [{"dealProducts":[{"pin":"","product":{"id":"100","code":"AAA","name":"AAA"}},{"pin":"","product":{"id":"200","code":"BBB","name":"BBB"}}]},{"dealProducts":[{"pin":"","product":{"id":"300","code":"CCC","name":"CCC"}},{"pin":"","product":{"id":"200","code":"BBB","name":"BBB"}},{"pin":"","product":{"id":"400","code":"DDD","name":"DDD"}},{"pin":"","product":{"id":"100","code":"AAA","name":"AAA"}}]}];;
    let selectedPIN = dp.pin;

    //Can this be made more efficient ????
       AllPackages.filter(pkg => pkg.dealProducts
        .filter(pkgDealProduct => pkgDealProduct.product.code === dp.product.code)
        .map(data => data.pin = selectedPIN));
}

Upvotes: 0

Views: 39

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371019

You can make it more efficient by not constructing an unnecessary intermediate array - your goal is to perform side-effects (mutate the data), not to construct a filtered array from the AllPackages, so use a generic iteration method like forEach or for..of instead of .filter in the outer loop.

Similarly, don't use .map, since you aren't looking to map to a new array - again, you're looking for side-effects, so use a generic iteration method.

You can also extract the code from the parameter just once, instead of on every iteration.

const { code, pin } = dp.product;
for (const pkg of AllPackages) {
    pkg.dealProducts
        .filter(pkgDealProduct => pkgDealProduct.product.code === code)
        .forEach((data) => {
            data.pin = pin;
        });
}

Upvotes: 2

Related Questions