Check if value exist in the array of objects and if it there update it

Viewed 4221

I am trying to check if the product with that id exist and if it is update quantity Pushing all of the created struct obj to and array of objects

contract TheStore is Ownable {
     
    struct Store {
        uint id;
        uint quantity;
    }

    mapping(address => Store[]) public productsId;
    Store[] public store;

    
    function addProduct(uint id,  uint quantity) public {
        if(id == store.id){
     product[id].quantity +=  quantity
    }
        store.push(Store({id: id ; quantity: quantity}));
    }

    function AllProducts() public view returns (Store[] memory)
    {
        return store;
    }

         
}```
1 Answers

With your currently defined variables, you can loop through all the existing store items until you've found the corresponding item, and then update it. If there's no corresponding item, you can create a new one:

function addProduct(uint id,  uint quantity) public {
    // loop through all `store` items until the item with the corresponding ID is found
    for (uint i; i < store.length; i++) {
        if (store[i].id == id) {
            // corresponding item found - update quantity and early return
            store[i].quantity += quantity;
            return;
        }
    }

    // no corresponding item found (the early return didn't invoke) - add the product to the store
    store.push(Store(id, quantity));
}

However, the code above is very inefficient and expensive to run gas-wise. So I'd recommend to add a mapping of existing product IDs to the store array indexes. Then you can simply query the mapping and get the resulting info whether the product ID exists (the value of the mapping is non-zero) or not:

mapping (uint => uint) productIdToArrayIndex;

function addProduct(uint id,  uint quantity) public {
    uint arrayIndex = productIdToArrayIndex[id];
    if (arrayIndex > 0) {
        // the product is stored in the `store[arrayIndex]`
        store[arrayIndex].quantity += quantity;
    }

    // no corresponding item found - add the product to the store, and add their index to the mapping
    store.push(Store(id, quantity));
    productIdToArrayIndex[id] = store.length - 1;
}
Related