Eric
Eric

Reputation: 207

How do I access an object by index in a knockout observablearray?

I have an observable array:

var myObservableArray = ko.observableArray([
    { name: "Car", price: "9999" },
    { name: "Shoes", price: "20" },
    { name: "Paper", price: "1" }
]);

I'm trying to access the price of the first item in the array.

<div data-bind="text: myObservableArray()[0]"></div>

Displays:

[object Object]

I've tried:

<div data-bind="text: myObservableArray()[0].price"></div>

But that just returns a null.

What's the correct syntax for doing this?

Edit: Fixed a copy and paste error pointed out below.

Upvotes: 13

Views: 16599

Answers (3)

Julien Brunelle
Julien Brunelle

Reputation: 21

wrong way.....

self.getvaluefrom = function (a ,b)

try catch return a valid value then add data-bind="text:getvaluefrom(a,b) if the item is not in the array you'll get a ko error....

ko html displays only a static valid entry of an array....

Upvotes: 0

Mattl
Mattl

Reputation: 1618

This could simply be down to you trying to access the first item of an array before the array has been populated.

Wrap your data-bind control with a simple if statement to check first:

<!-- ko if: (myObservableArray().length > 0) -->
    <div data-bind="text: myObservableArray()[0].price"></div>
<!-- /ko -->

Upvotes: 1

Kyeotic
Kyeotic

Reputation: 19867

Other than using the wrong property name, developerexampledata instead of myObservableArray, your code is just fine.

Here is a working fiddle

Upvotes: 7

Related Questions