Knockout.js ko.mapping.fromJS销毁数组成员

Knockout.js ko.mapping.fromJS销毁数组成员,knockout.js,knockout-mapping-plugin,Knockout.js,Knockout Mapping Plugin,我需要使用ko.mapping.fromJS用数据填充模型。当我运行下面的代码片段()时,一切正常:people.firstName被更新,新的prop2属性被添加到模型中 var Person = function() { this.lastName = ko.observable('lastName'); this.firstName = ko.observable('firstName'); }; var DataModel = function(

我需要使用
ko.mapping.fromJS
用数据填充模型。当我运行下面的代码片段()时,一切正常:
people.firstName
被更新,新的
prop2
属性被添加到模型中

var Person = function() {
        this.lastName = ko.observable('lastName');
        this.firstName = ko.observable('firstName');
    };

var DataModel = function() {
        this.people = ko.observable(new Person());
        this.prop1 = ko.observable('prop1');
    };

var vm = function(){
    this.data = new DataModel();
    this.log = function(){
        console.log(this.data, this.data.people());
    };
    this.update = function(){
        ko.mapping.fromJS(
            {
                people: { firstName: 'firstName updated'},
                prop2: 'prop2'
            }
            ,{}, this.data);
    }
 };

ko.applyBindings(new vm());
然后我想通过将
people
转换为array(),稍微改变一下模型:

现在坏事情发生了:
people
对象被销毁并替换为
[{firstName:'firstName updated'}]
,丢失了
lastName
,而不是仅仅更新
firstName

任何人都可以解释这种行为的原因,以及在这种情况下更新模型的正确方法?

中描述了这种情况:要映射对象(即虚拟机的属性,即对象),通常需要指示
ko.mapping
如何创建(或比较)这些对象,例如,通过提供
create
功能:

ko.mapping.fromJS(
    {
        people: [{ firstName: 'firstName updated'}]
    }
    ,{
        'people': {
            create: function (options) {
                return new Person(options.data)
            }
        }
    }, this.data);
有关解决方案,请参见以下小提琴:

ko.mapping.fromJS(
    {
        people: [{ firstName: 'firstName updated'}]
    }
    ,{
        'people': {
            create: function (options) {
                return new Person(options.data)
            }
        }
    }, this.data);