3

We're using knockout.js heavily in our app, but have run into a new scenario. It revolves around ko.toJSON, but it appears to be the underyling ko.toJS that's causing the problem.

We have an object with a number of properties, one of which is an array of other objects. After running it through ko.toJS, it becomes an object with each property given the name of the original index. I've not been able to replicate this in test code - indeed ko.toJS properly keeps an array as an array in my other tests.

Example of ko.toJS getting it wrong and converting it to an object:

enter image description here

Example of ko.toJS getting it right, and leaving it as an array:

enter image description here

Any thoughts on why ko.toJS may be causing this or what to look at next appreciated...!

Update

When using the debugger version of knockout, this is how it's reporting the Array being passed in to mapJsObjectGraph:

enter image description here

3
  • You could download the knockout debug build and look for the function mapJsObjectGraph (line 1619 in my knockout-3.0.0-debug). Then add a console.log(outputProperties) above the line (1650 for me) return outputProperties; and just see what KO is generating as it goes along. Commented Jul 22, 2014 at 14:47
  • Thanks @sifriday - updated info added. We've just found something ourselves also - the object is originating outside of our iframe, it seems instanceof doesn't work across frame boundaries. Will post an answer if this is the case. Commented Jul 22, 2014 at 15:09
  • 1
    @JamesThorpe It's certainly the issue. instanceof compares references of prototypes and the Array prototype (as with all other objects) is unique for each host environment. Commented Jul 22, 2014 at 15:11

1 Answer 1

6

This is a bug in knockout. An issue has already been opened.

The workaround is to change the line in the function mentioned above, mapJsObjectGraph:

var outputProperties = rootObject instanceof Array ? [] : {};

to this:

var outputProperties = toString.call(rootObject) === "[object Array]" ? [] : {};

Seems that this isn't the only place instanceof is used in knockout though, as per the bug report.

Sign up to request clarification or add additional context in comments.

1 Comment

I will be, as soon as SO lets me :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.