让我们举个例子,我们有父元素和相应的子元素。 所以,我在javascript中有一个父类和一个子类:
//代表父母的类
function parent(data) {
this.Id = ko.observable(data.Id);
this.Name = ko.observable(data.Name);
this.children = ko.observableArray([]);
}
//代表孩子的类
function child(data) {
this.Id = ko.observable(data.Id);
this.Name = ko.observable(data.Name);
this.Age = ko.observable(data.Age);
this.ParentID = ko.observable(data.ParentID);
}
实际上,我可以通过
附加与每个父母相关的孩子 Jquery.getJSON("/api/parents", function (allData) {
var mappedParents = Jquery.map(allData, function (item) {
return new parent(item)
});
self.parents(mappedParents);
// Get Children and attach them to the corresponding parent
Jquery.getJSON("/api/children", function (allData) {
var mappedChildren = Jquery.map(allData, function (item) {
return new child(item)
});
self.children(mappedChildren);
ko.utils.arrayForEach(mappedChildren, function (dataChildren) {
var children_ParentID = dataChildren.ParentID();
ko.utils.arrayForEach(self.parents(), function (parent) {
if (parent.Id() == children_ParentID) {
parent.children.push(new child(dataChildren));
}
});
});
});
});
我终于得到一个Json,其中包含与每个父项相关的可观察子项数组。
parent :
[
{
"Id": 1,
"Name": "Parent1",
"children": [
{"Id": 1, "Name": "Child11", "Age": "11", "ParentID": 1},
{"Id": 2, "Name": "Child12", "Age": "12", "ParentID": 1},
{"Id": 3, "Name": "Child13", "Age": "13", "ParentID": 1}
]
},
{
"Id": 2,
"Name": "Parent2",
"children": [
{"Id": 4, "Name": "Child11", "Age": "21", "ParentID": 2},
{"Id": 5, "Name": "Child12", "Age": "22", "ParentID": 2}
]
}
]
因此,正如您所看到的,我能够通过嵌套循环将子项附加到给定父级
foreach parents
{
var idParent = Id;
foreach children
{
if chidren.parentId == idParent then attach children
}
}
但是,我确定,可能有更好的方法来做到这一点,这样更有效率。例如,映射插件?还是更好的东西?因为如果有大量数据,将所有孩子都拉到每个父母身上可能需要一些时间。
答案 0 :(得分:0)
以下方法建议先让所有的孩子,然后让所有的父母。然后从原始子数组中过滤子节点中的特定父节点。
var parent = function(data) {
var myself = this;
this.Id = ko.observable(data.Id); //I assume this is same as the parentId property in a child object.
this.Name = ko.observable(data.Name);
this.children = ko.observableArray(self.getChildByParentId(this.Id));
}
var child = function(data) {
var myself = this;
this.Id = ko.observable(data.Id);
this.Name = ko.observable(data.Name);
this.Age = ko.observable(data.Age);
this.ParentID = ko.observable(data.ParentID);
}
self.getChildByParentId = function(parentId) {
var children = ko.utils.ArrayFilter(self.children(), function(child) {
return child.ParentId === parentId;
});
return children;
}
Jquery.getJSON("/api/children", function(allData) {
var mappedChildren = Jquery.map(allData, function(item) {
return new child(item);
});
self.children(mappedChildren);
});
Jquery.getJSON("/api/parents", function(allData) {
var mappedParents = Jquery.map(allData, function(item) {
return new parent(item);
});
self.parents(mappedParents);
});
我仍然不确定这是否是你所期望的答案,但仍然可以给出一个机会......