Solidity – How to Map a List in Smart Contracts

contract-developmentremixsolidity

I have a Map of a List. I am managing the data in the map and the list. I have it working for now, but wanted to find out if there is a better way to do this.

mapping (bytes32 => Receipts[]) receiptsByPersonMap;
Receipts[] dummyReceiptsList;

Receipts newReceipt = new Receipts(_person, _cost);

dummyReceiptsList = receiptsByPersonMap[_person];

dummyReceiptsList.push(newReceipt);
receiptsByPersonMap[_person] = dummyReceiptsList;

This works for now. it seems that the last line is irrelevant – if receiptsList is pointing to the same storage space. Any suggestion of a better way to do this.

Best Answer

Why not do it in one go? Something like:

receiptsByPersonMap[_person].push(new Receipts(_person, _cost));

Incidentally, this may just be an artifact of the way you've simplified the question to post here, but since _person is the key of the mapping where you store your Receipts record, you can't access it unless you already know _person, so you should be able to remove _person from the struct. At that point the struct only contains one item, so you could get rid of it entirely and just store cost in a bytes32 => uint256[] mapping.