Norbert
Norbert

Reputation: 2771

Knockout.js – Getting the Object Data

I just started playing around with knockout and I have a question. Here's part of the code:

function Task(data) {
    var self = this;
    self.name = ko.observable(data.name);
}

function ViewModel() {
    self.taskArr = ko.observableArray([
    // some default data
    new Task({ name: "to-do 1"}),
    new Task({ name: "to-do 2"}),
    new Task({ name: "to-do 3"})
]);

Basically, I'm trying to display the contents of the object via console.log(). But when I use console.log(self.taskArr()); I get [Task, Task, Task] as a result.

Using self.taskArr()[0].name will only get the first result, not all of them.

Upvotes: 1

Views: 1281

Answers (2)

Norbert
Norbert

Reputation: 2771

In order to display the data of an observable array, you'll have to use the ko.toJSON function, like so:

console.log(ko.toJSON(self.taskArr()));

which will output:

[{"name":"to-do 1"},{"name":"to-do 2"},{"name":"to-do 3"}] 

More info here: http://knockoutjs.com/documentation/json-data.html

Upvotes: 2

giaour
giaour

Reputation: 4071

Try converting the Task objects to JSON strings:

    console.log(JSON.stringify(self.taskArr()));

Upvotes: 1

Related Questions