Check that object is null in solidity mapping
Asked Answered
Y

3

10

I have this solidity mapping

mapping (string => Ticket) public myMapping;

I want to check if myMapping[key] exists or not. How can I check?

Yehudi answered 22/12, 2019 at 22:1 Comment(0)
L
16

The entire storage space is virtually initialized to 0 (there is no undefined). So you have to compare the value to the 0 value for your type. For example, mapping[key] == address(0x0) or mapping[key] = bytes4(0x0).

Lupine answered 24/12, 2019 at 1:54 Comment(0)
C
8

There is no direct method to check whether the mapping has particular key. But you can check if mapping property has value or not. The following example considered that the Ticket is the struct with some property.

pragma solidity >=0.4.21 <0.6.0;

contract Test {

    struct Ticket {
       uint seatNumber;
    }

    mapping (string => Ticket) myMapping;

    function isExists(string memory key) public view returns (bool) {

        if(myMapping[key].seatNumber != 0){
            return true;
        } 
        return false;
    }

    function add(string memory key, uint seatNumber) public returns (bool){            
        myMapping[key].seatNumber = seatNumber;            
        return true;
    }
}
Covert answered 23/12, 2019 at 12:16 Comment(0)
P
0
pragma solidity ^0.8.0;
contract BookLibNew{

    address public owner;

    constructor() public{
        owner = msg.sender;
    }
    modifier onlyOwner(){
        require(msg.sender == owner);
        _;
    }

    struct bookDet{
        uint bookId;
        string bookTitle;
        string bookAuthor;
    }

    mapping (uint8 => bookDet) public bookLib;
    function addBookLib(uint8 _bookId, string memory _bookTitle, string memory _bookAuthor) 
    public onlyOwner {
        require(bookLib(_bookId) == false, "Error: Book already exists");
        bookLib[_bookId].bookTitle = _bookTitle;
        bookLib[_bookId].bookAuthor = _bookAuthor;
    }

    function readBookDetails(uint8 _bookId) public view returns(string memory, string memory){
        return(bookLib[_bookId].bookTitle, bookLib[_bookId].bookAuthor);
    }
}
Pete answered 13/8, 2022 at 12:8 Comment(2)
I am getting type error in this is line of code "require(bookLib(_bookId) == false, "Error: Book already exists");" here i trying to check whether the book has already added or not. How can i check here?Pete
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Wanderjahr

© 2022 - 2024 — McMap. All rights reserved.