Console logging Observable array objects

1,899 views
Skip to first unread message

ro...@blue-fly.co.uk

unread,
Nov 27, 2014, 8:04:17 AM11/27/14
to knock...@googlegroups.com
Hi,

Is there a way to console log these out?

I create my observable array of objects

   var anotherObservableArray = ko.observableArray();
  
var count = 0;
   $.each(data.posts, function(key, item) {
    count = count++;
    anotherObservableArray.push( {
    artist: JSON.parse(data.posts[count].custom_fields.Artist[0]), 
    title: data.posts[count].title } );
    }); 



This works

 console.log("it is"+anotherObservableArray()[0]['title']);


but I want the whole lot

 console.log("it is"+anotherObservableArray());

This just returns 

 it is [object Object],[object Object]

There are 2 objects being returned.


Many thanks,









 

rpn

unread,
Nov 27, 2014, 9:33:15 AM11/27/14
to knock...@googlegroups.com, ro...@blue-fly.co.uk
Hello-
When you do your console.log, you will want to separate the arguments, so that it does not try to build a single string, so like:

console.log("it is", anotherObservableArray());

If the items inside of your observableArray contain observables themselves, then you might want to do a ko.toJS on it first like:


console.log("it is", ko.toJS(anotherObservableArray));

This will ensure that all observable are unwrapped and you get a plain, old JavaScript object in the console.

Finally, another option is to convert it all the way to a stringified representation using ko.toJSON. It would look like:

console.log("it is", ko.toJSON(anotherObservableArray));

The whole object would be shown as a string, but you would not be able to drill into the object like before. Additional arguments that get passed to ko.toJSON are passed on to JSON.stringify, so to get better formatting you would do:

console.log("it is", ko.toJSON(anotherObservableArray, null 2));

Just a few options. Generally in the console. ko.toJS is a good option.

Hope that helps.

-Ryan
Reply all
Reply to author
Forward
0 new messages