sr28
sr28

Reputation: 5106

How can I retrieve a value from an observable array that contains a custom type?

I have a view model property called DiscountValues that's an Ilist, which is a list of a custom type, let's call it MyCustomType. This type has 2 properties; public int Year and public decimal Discount.

All the data in this view model, including DiscountValues is data bound using Knockout, and using developer tools I can see the values coming through in the following format:

DiscountValues: [
    {"Year":1, "Discount":0.0500},
    {"Year":2, "Discount":0.1200},
    {"Year":3, "Discount":0.2500}
]

My question is, how can I access the Discount value for a given index, say I want ONLY the Discount value of 0.02500 for year 3?

I tried the following:

<span data-bind="text:MyDiscountValues()[2].value"></span>

However nothing gets displayed. My guess is that it's not just 1 key value pair, but 2 for each entry, so key: Year value: 3 is one kv pair and key:Discount value:0.02500 is the second kv pair. If that's right, how can I get the value for the 2nd KV only?

I'm not sure this will impact it (I'm thinking not) but this is being done inside a resx file.

Upvotes: 1

Views: 33

Answers (1)

PatrickSteele
PatrickSteele

Reputation: 14677

Your indexing syntax is correct, but you'll be accessing the actual object with Year and Discount properties so you can reference them directly.

<span data-bind="text:MyDiscountValues()[2].Discount"></span>

Upvotes: 3

Related Questions