How to get a particular value from a map

79 views Asked by At

In my contract I have a map with a principal as its key and a tuple as its value. I want to get a particular value from the value-tuple for every principal in the map. Let's say I want to get the salary for every member from the map below. (define-map members principal {position: (string-ascii 30), salary: uint})

2

There are 2 answers

1
eborrallo On

You need to use map-get

Check this examples

;; A map that creates a principal => uint relation.
(define-map balances principal uint)

;; Set the "balance" of the tx-sender to u500.
(map-set balances tx-sender u500)

;; Retrieve the balance.
(print (map-get? balances tx-sender))

Or

(define-map orders uint {maker: principal, amount: uint})

;; Set two orders.
(map-set orders u0 {maker: tx-sender, amount: u50})
(map-set orders u1 {maker: tx-sender, amount: u120})

;; retrieve order with ID u1.
(print (map-get? orders u1))
0
Kenny On

You can use Clarity's get function in conjunction with map-get:

Example:

(define-map members principal {position: (string-ascii 30), salary: uint})

(map-set members 'ST3QFME3CANQFQNR86TYVKQYCFT7QX4PRXM1V9W6H {position: "test", salary: u500})

(print (get salary (map-get? members 'ST3QFME3CANQFQNR86TYVKQYCFT7QX4PRXM1V9W6H)))

And a link to Clarity's get function demonstrating this usage: https://docs.stacks.co/docs/write-smart-contracts/clarity-language/language-functions#get

However, you can't iterate through a map, you need to know the key to look up data, so if you wanted to iterate, you would need a list of all the principals and iterate through that using the map function, looking up the corresponding principal in the map on each iteration.