Get nth item from observable array
Have you tried data-bind="text: pdfs()[nth].name"
?
Take a look at "Reading information from an observableArray" on this page: http://knockoutjs.com/documentation/observableArrays.html. If pdfs
is an observable array, then to get the underlying array (so that you can index into it using []), you need to call the function. Thus, the ().
Ojame
Updated on June 15, 2022Comments
-
Ojame about 2 years
I'm learning Knockout, and have an
pdfs
observable array which consists of 4 items. I need the HTML output of the items to look like this:Intro Text [Item 1].name is located in [Item 1].location Some links, other body text [Item 2].name is located in [Item 2].location [Item 3].name is located in [Item 3].location [Item 4].name is located in [Item 4].location
I've found a few places that reference
data-bind="text: pdfs[nth].name"
but if I do this I get 'pdfs is not defined' or similar. I realise I could use two foreach loops and the<!-- ko if: $index() == nth -->
but surely there has to be a better way?It seems like something a few people would want to do, so I hope theres a robust solution. I realise I'm talking about the first item here (and everything else could just be looped out in the
foreach
), but I'm interested overall fornth
(if I want to put say, item 3 somewhere special).*I don't really want to create a custom binding, if possible