[Ethereum] How to create an iterable key->value structure in Solidity

dapp-developmentmappingstruct

I am trying to create a framework for users to offer generic goods for sale. For example, a single generic item (a Gizmo) might have 14 people selling it for different prices and from different parts of the world. To enable this, I need to manage a list of prices, kept in storage, that can be queried by a web3.js-driven frontend.

Something like a mapping would be best:

uint productId;  // Set automatically for each product
uint memberId;  // Set automatically at join
uint price;  // Prices are in US cents

/* (productId => (memberId => price)) */
mapping (uint => mapping (uint => uint)) priceLedgers;

/* Pseudo-JavaScript below */
for (var i=0, i < priceLedgers[productId].length, i++) {
    // List of members with their prices here.
}

Maybe aonther way to explain what I am trying to do is with Python.

priceOffers = {}
priceOffers[1] = 234
priceOffers[45] = 99392
priceOffers[23] = 111

>>> priceOffers
{1: 234, 45: 99392, 23: 111}

>>> for key, value in priceOffers.iteritems():
    print(key, value)
(1, 234)
(45,99392)
(23, 111)

productId = 34
priceLedgers = {}
priceLedgers[34] = priceOffers

Is this possible in Solidity?

Best Answer

You could just store the index of the mapping in an array.

uint[] indexes;
mapping (uint => uint) example;

function add(uint x){
  example[indexes.length] = x;
 indexes.push(indexes.length);
}

Then just iterate over the array index as key.

if you want custom unordered keys, it's the same. You would just need to pass the key in the add function

function add(uint data,uint index){
  example[index] = data;
  indexes.push(index);
}
Related Topic