我想将多个json数据合并到一个vm中。我读过你可以多次从js映射到模型中它应该合并但是在我的情况下,它不是。它正在取代数据。
function Item(ID, Name, Description) {
this.ID = ko.observable(ID);
this.Name = ko.observable(Name);
this.Description = ko.observable(Description);
}
var MasterViewModel = {
model: ko.observableArray([])
};
$.getJSON(url, function (response) {
ko.mapping.fromJS(response["TM1.Cube"], Item, MasterViewModel.model);
ko.mapping.fromJS(response["TM1.Dimension"], Item, MasterViewModel.model);
})
ko.applyBindings(MasterViewModel);
这是我的json数据
{
"LogicalName": "TM1.Model",
"ID": "12345",
"Name: "Sample",
"TM1.Cube": [
{
"LogicalName": "TM1.Cube",
"ID": "111111",
"Name": Assets"
},
{
"LogicalName": "TM1.Cube",
"ID": "111112",
"Name": Finance"
}
],
"TM1.Dimension": [
{
"LogicalName": "TM1.Dimension",
"ID": "222221",
"Name": Assets"
},
{
"LogicalName": "TM1.Dimension",
"ID": "222222",
"Name": Finance"
}
]
}
我预期的结果是这样的
{
"LogicalName": "TM1.Cube",
"ID": "111111",
"Name": Assets"
},
{
"LogicalName": "TM1.Cube",
"ID": "111112",
"Name": Finance"
},
{
"LogicalName": "TM1.Dimension",
"ID": "222221",
"Name": KPI"
},
{
"LogicalName": "TM1.Dimension",
"ID": "222222",
"Name": Default"
}
我添加了一个jsFiddle http://jsfiddle.net/e1ppj3qc/1/
答案 0 :(得分:0)
映射插件可以采用现有模型,但我认为它不会合并数据。
例如,你可以像这样映射两次:
{one: "yo"}
和
{two: "dawg"}
进入同一个模型,你现在有两个observable,一个()和两个()
但如果你这样做(你是):
{one: ["yo"]}
和
{one: ["dawg"]}
它将始终覆盖匹配的属性。 您可以改为执行映射,然后只需按下即可插入要添加的数组:
function pushCubs(dataToPush) {
ko.utils.arrayPushAll(MasterViewModel.modelcub, dataToPush());
}
pushCubs(ko.mapping.fromJS(data));
pushCubs(ko.mapping.fromJS(data2));