Search code examples
knockout.jsknockout-mapping-plugin

Using fromJS on an array with empty strings will replace those strings with false


When the object below is mapped, the empty "" values in the array are mapped as false in the observable array:

var d2 = {
    "values": [{"9", false, "", true, null, "", "", ""]
};

var viewmodel2 = ko.mapping.fromJS(d2);

When mapped back to json using ko.mapping.toJSON(viewmodel2); this is the result:

{ "values": [
    "9",
    false,
    false,
    true,
    null,
    false,
    false,
    false] }

Notice that the last 3 string values from the array are converted back to false.

Is this a bug? or are arrays containing bools and strings not supported

Here's a fiddle for this.


Solution

  • This was indeed a bug and is now fixed. It was caused by two things:

    • The equality comparison to see which keys were contained in an array was using the "==" operator instead of "===" so it considered "false" and "" to be the same key.
    • Second, I sort all keys in the array as part of the duplicate key handling logic. However this is not something that should be done when you don't explicitly provide a key callback, since you probably care about the order of the items in that case.

    The latest version, 1.2.3, is available at GitHub and a NuGet package was also created. The reproduction jsfiddle kindly created by Srluisreyes now also works!