【发布时间】:2017-06-20 17:11:29
【问题描述】:
我有如下嵌套数组的 JSON
[
{
"Amount": 3250,
"CustomerAccountNumber": 1,
"EntityName": "a",
"Id": 1,
"IsValidationSuccess": false,
"IsWorkInProgress": true,
"ValidationErrors": [
{
"CreationDate": "2017-01-23T00:00:00",
"Reason": "Error1"
},
{
"CreationDate": "2017-01-23T00:00:00",
"Reason": "error2"
}
]
},
{
"Amount": 450,
"CustomerAccountNumber": 1,
"EntityName": "s",
"Id": 4,
"IsValidationSuccess": false,
"IsWorkInProgress": true,
"ValidationErrors": [
{
"CreationDate": "2017-01-23T00:00:00",
"Reason": "error"
}
]
},
{
"Amount": 5600,
"CustomerAccountNumber": 2,
"EntityName": "f",
"Id": 2,
"IsValidationSuccess": false,
"IsWorkInProgress": true,
"ValidationErrors": [
{
"CreationDate": "2017-01-23T00:00:00",
"Reason": "error"
}
]
}
]
-
然后我按客户编号和 entityEntityName 分组,并使用这给我以下 JSON 填充模型可观察数组
[ { “计数”:2, "客户帐号": 1, “实体”:[ { “计数”:1, “实体”: [ [对象对象] ], "实体名称": "a", “总和”:3250 }, { “计数”:1, “实体”: [ [对象对象] ], “实体名称”:“b”, “总和”:450 } ], “总和”:3700 }, { “计数”:1, “客户帐号”:2, “实体”:[ { “计数”:1, “实体”: [ [对象对象] ], “实体名称”:“c”, “总和”:5600 } ], “总和”:5600 } ]然后当我需要返回 JS 时,TOJ 不会映射嵌套数组,而是 html 中的模型绑定与敲除会正确绑定数据。
komapping.toJS(viewModel.result())
给我以下结果 - 它不映射嵌套数组,我们有什么办法可以解决这个问题吗?
更新
viewModel = function () {
var self = this;
self.transactionLines = ko.observableArray();
self.result = ko.observableArray();
}
AJAX 加载后,我在分组后将对象推送到 observableArray
var byAccountNo = groupBy(data, function (item) {
return [item.CustomerAccountNumber];
});
_.each(byAccountNo, function (item) {
var byEntity = groupBy(item, function (i) {
return [i.EntityName];
});
var obj = {
CustomerAccountNumber: item[0].CustomerAccountNumber,
Entities: ko.observableArray()
};
_.each(byEntity, function (itemEntity) {
var objByEntity = {
EntityName: itemEntity[0].EntityName,
Entity: ko.observableArray()
};
_.each(itemEntity,
function (inner) {
var result = ko.mapping.fromJS(inner);
self.transactionLines.push(result);
objByEntity.Entity.push(result);
});
objByEntity.Sum = ko.pureComputed({
read: function () {
var total = 0;
_.each(objByEntity.Entity(), function (item) {
total += item.Amount();
});
return total;
},
owner: objByEntity
});
objByEntity.Count = ko.pureComputed({
read: function () {
return objByEntity.Entity().length;
},
owner: objByEntity
});
obj.Entities.push(objByEntity);
});
obj.Sum = ko.pureComputed({
read: function () {
var total = 0;
_.each(obj.Entities(), function (item) {
total += item.Sum();
});
return total;
},
owner: obj
});
obj.Count = ko.computed({
read: function () {
var total = 0;
_.each(obj.Entities(), function (item) {
total += item.Count();
});
return total;
},
owner: obj
});
self.result.push(obj);
});
};
【问题讨论】:
标签: knockout.js knockout-mapping-plugin