简体   繁体   English

ko.toJS将数组转换为对象

[英]ko.toJS converting Array to Object

We're using knockout.js heavily in our app, but have run into a new scenario. 我们在应用程序中大量使用基因敲除(knockout.js),但遇到了新情况。 It revolves around ko.toJSON , but it appears to be the underyling ko.toJS that's causing the problem. 它围绕ko.toJSON ,但似乎是引起问题的ko.toJS ko.toJS

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. 通过ko.toJS运行它ko.toJS ,它将成为一个对象,每个属性都具有原始索引的名称。 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. 我无法在测试代码中复制它-实际上ko.toJS在其他测试中正确地将数组保留为数组。

Example of ko.toJS getting it wrong and converting it to an object: ko.toJS将其错误并将其转换为对象的示例:

在此处输入图片说明

Example of ko.toJS getting it right, and leaving it as an array: ko.toJS正确将其保留为数组的示例:

在此处输入图片说明

Any thoughts on why ko.toJS may be causing this or what to look at next appreciated...! 关于为什么ko.toJS可能导致此问题或接下来要看的内容的任何想法……!

Update 更新

When using the debugger version of knockout, this is how it's reporting the Array being passed in to mapJsObjectGraph: 使用敲除程序的调试器版本时,这就是它报告将数组传递给mapJsObjectGraph的方式:

在此处输入图片说明

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: 解决方法是更改​​上述函数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. 根据错误报告,这似乎并不是在淘汰赛中使用instanceof的唯一地方。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM