Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/404.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用来自第二个源的数据扩展ObservalArray_Javascript_Knockout.js_Knockout Mapping Plugin - Fatal编程技术网

Javascript 使用来自第二个源的数据扩展ObservalArray

Javascript 使用来自第二个源的数据扩展ObservalArray,javascript,knockout.js,knockout-mapping-plugin,Javascript,Knockout.js,Knockout Mapping Plugin,我从一个Ajax源代码创建了一个observableArray,它运行得非常好。现在我想用第二个源的数据扩展一些数组项 例如: { id: 1, name: 'Hugo', age: 18 } 。。。稍后我想补充: { id: 1, city: 'New York', country: 'US' } 。。。这将导致: { id: 1, name: 'Hugo', age: 18, city: 'New York', country: 'US' } 使用ko.mapping插件可以做到这一点

我从一个Ajax源代码创建了一个observableArray,它运行得非常好。现在我想用第二个源的数据扩展一些数组项

例如:

{ id: 1, name: 'Hugo', age: 18 }
。。。稍后我想补充:

{ id: 1, city: 'New York', country: 'US' }
。。。这将导致:

{ id: 1, name: 'Hugo', age: 18, city: 'New York', country: 'US' }
使用ko.mapping插件可以做到这一点吗?我已经做了一些测试,结果是数组中项目的映射属性已被第二个源的属性替换


解决方案

其实这很容易解决。使用映射插件添加新数据时,我只需检查
。现有数据只是使用附加数据进行扩展

ko.mapping.fromJS(modifications, {
    key: function(data) {
        return ko.unwrap(data.id);
    }
}, originalData);

如果属性不可观察,则可以使用ko.utils.extend

var original = { id: 1, name: 'Hugo', age: 18 };
var modifications ={ id: 1, city: 'New York', country: 'US' };


var result2 =  ko.utils.extend(original,  modifications);

console.log(JSON.stringify(result2));