How to check value or object exists in Solidity mapping?
This tutorial explains how to check object that exists in Solidity mapping.
Mapping in solidity is a similar to hash table in java.
It stores keys and values, each key holds value types(primitive types) and value types are reference types(struct, nested mapping, array objects).
Every key is mapped to value in a solidity. If the value does not exist, means the value is zero.
There are null
or undefined
or empty
object concepts in solidity.
Mapping values are initialized with valid typed values.
The uninitialized value of a mapping object is zero.
How to check object is null in solidity mapping?
Mapping stores the key and value, in such a way that every valid key is mapped to value default byte representation of zero values.
Let’s declare a struct Employee that contains the ID of uint
and name of string
type
uint id;
string name;
}
Let’s store the struct in mapping with a string key
So, Declared and defined the mapping
structure.
mapping (string => Employee) employees;
It stores string as key and value as struct Employee.
The string is mapped to the byte representation of struct default values.
Unlike other languages(java, JavaScript), There is null or undefined in solidity.
Values are assigned to zero bytes if there is no object.
If a reference type exists such as an array or struct, the values are default byte zero representation.
To check in object exists, mapping[key]== address(0x0000000000000000)
Here is an example code to check object is null or not in solidity
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;
contract Test {
struct Employee {
uint id;
string name;
}
mapping (string => Employee) employees;
function isMappingObjectExists(string memory key) public view returns (bool) {
if(employees[key].id > 0){
return true;
}
else{
return false;
}
return false;
}
}
This contains isMappingObjectExists
function that returns true if the object is not null, returns false.
First, get the value of an object using syntax mapping[key]
, and it returns a struct
object.
It checks a struct object property value greater than zero(0).
Another way is to check the bytes
length of an object is zero or not.
function isMappingObjectExists(string memory key) public view returns (bool) {
if(bytes(employees[key]).length>0){
return true;
}
else{
return false;
}
return false;
}
This approach calculated the bytes of an object from a given mapping key, and checked the length of the bytes object is greater than zero(0)
Conclusion
As a result, Check mapping value object exists or not using the below approaches
- Check object properties value is zero
- Check bytes the object length is zero or not