How to check value or object exists in Solidity mapping?
This tutorial explains how to check whether an object exists in a Solidity mapping.
In Solidity, a mapping
is similar to a hash
table in Java. It stores keys
and values
, with each key
holding value types (primitive types) and value
types representing reference types (such as structs, nested mappings, and array objects).
Every key is mapped to a value
in Solidity. If the value does not exist, it means the value is zero.
In Solidity, concepts like null
, undefined
, or empty
objects exist.
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?
A mapping stores keys and values in such a way that every valid key is mapped to the default byte representation of zero values.
Let’s declare a struct called Employee
that contains the ID
of type uint
and the name
of type string
struct Employee {
uint id;
string name;
}
Let’s store the struct
in a mapping with a string key. So, we declare and define the mapping
structure
mapping (string => Employee) employees;
It stores a string as the key and a struct Employee
as the corresponding value.
The string
is mapped to the byte representation of the struct’s default values.
Unlike other languages (Java, JavaScript), there is no 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 default to the zero byte representation.
To check if an object exists, use the expression mapping[key] == address(0x0000000000000000).
Here is an example code to check if an 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 includes the isMappingObjectExists
function, which returns true
if the object is not null and false
otherwise.
First, obtain the value of an object using the syntax mapping[key], which returns a struct object.
The function then checks whether a property value of the struct object is greater than zero (0).
Another approach is to examine whether the bytes length of the 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 calculates the bytes of an object based on a given mapping key and checks whether the length of the bytes object is greater than zero (0).
Conclusion
As a result, verify the existence of a mapping value object using the following approaches:
- Check if the object properties’ values are zero.
- Check if the length of the object’s bytes is zero or not.