Loading...
Ususally we use struct and other data types to store multiple properties. But calling those for larger iteration is very difficult and ruins quality of our dapps. 2d arrays can help us solve those problems. Note that for multidimentional arrays data type remains constant unlike struct.
We will take a look at 2d arrays in this smartbook. Smart contract we will be building will store different key, value pairs for different user public addresses
We will map our 2d array with address, it will store different key value pairs for a user.
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;
contract key_val{
mapping(address => string[][]) private key_val_pairs;
}
Let's create a function which will take those key value pairs from user and save it in our 2d array.
function save(string memory _key, string memory _value) public{
key_val_pairs[msg.sender].push([_key, _value]);
}
Everytime user saves key values , array will store a key value paired array thus we can retrieve all the saved pairs at once.
function get_pairs() public view returns(string [][] memory){
return key_val_pairs[msg.sender];
}
Suppose if we would have saved these pairs in an struct , we would have needed to call this function for each pair stored in the stuct. But this way all the pairs can be called at onve. It have some limitations but most of the cases it is useful to tackle some simple problems.
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;
contract key_val{
mapping(address => string[][]) private key_val_pairs;
function save(string memory _key, string memory _value) public{
key_val_pairs[msg.sender].push([_key, _value]);
}
function get_pairs() public view returns(string [][] memory){
return key_val_pairs[msg.sender];
}
}