0

I would like to create a Map total which can be used like: total['cashBalance'].sum

based on existing data

const fields = ['cashBalance', 'openTradeEquity', 'initialMargin', 'optionValue', 'treasuries', 'margin'];    

I am trying as below but it is not working.

const total: Map<string, {sum: number}> = fields.map(f => [f, {sum: 0}]) ;

Surely, I am not getting the syntax right... can anyone please help me with this? Thanks Anand

2
  • Please clarify It's not working Commented Apr 6, 2018 at 13:05
  • Did you mean "but it is not working"? Also, instead of saying "it's not working", it would be more helpful to give an error message, or the result you got instead of what you expected. Commented Apr 6, 2018 at 13:07

1 Answer 1

3

The array's map function creates a new array from an existing one, and doesn't create a map. Here, you want to use the Map object instead. Loop through all of the items in fields and add an item to the map for each one.

const total = new Map<string, { sum: number }>()
for (const field of fields) {
  total.set(field, { sum: 0 })
}

total.get('cashBalance').sum // 0
Sign up to request clarification or add additional context in comments.

3 Comments

Shorter: const total: Map<string, { sum: number }> = new Map(fields.map(f => [f, { sum: 0 }] as [string, { sum: number }]));. Unfortunately the type cast is necessary.
I'd rather go with the readable approach over the shorter one
Thank you so much @kingdaro

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.