Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

knockout.js

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.

like image 228
Eric Avatar asked Apr 18 '13 18:04

Eric


2 Answers

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

Here is a working fiddle

like image 200
Kyeotic Avatar answered Oct 22 '22 16:10

Kyeotic


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 -->
like image 1
Mattl Avatar answered Oct 22 '22 17:10

Mattl