在 Knockout 中合并数组
Merging arrays in Knockout
在我的淘汰赛应用程序中,我有两个可观察数组。一是地点,
self.locations = ko.observableArray([]).withIndex('id');
这包含所有位置。这些位置可以与项目相关联,也可以不相关联。如果项目中不存在位置,则项目 ID 将为空。
另一个数组是项目。它包含所有项目,如果它们有任何位置它有一个位置数组。
现在我要做的是得到一个数组,其中包含两个类似这样的东西
displayLocations = {
location1 = {name = "abc", ...}
... these don't have any projects
location9 = {name = "xyz", projectName = "project1", .. }
}
我正在尝试为此创建一个计算 属性,然后在视图方面,我正在考虑根据位置是否有项目使用不同的模板。
有什么建议吗?
不确定 withIndex
方法,但是使用 vanilla KO 可以在 computed
:
中使用 ko.utils.arrayMap
this.associatedLocations = ko.computed(function() {
var dataLoc = this.locations(),
dataProj = this.projects(),
result = ko.utils.arrayMap(dataLoc, function(loc) {
var newObj = loc, project;
if (loc.projectId !== null) {
project = ko.utils.arrayFirst(dataProj, function(proj) {
return proj.id === loc.projectId;
});
newObj.projectData = proj;
}
return newObj;
});
return result;
}, this);
// assumes locations have a 'projectId' & 'name' property, & projects an 'id' property
// will return an array in the form of
// [ {name: 'xyz', projectData: { id: ..., projectName: ...}}]
您可以通过执行以下操作来测试位置是否与项目相关联:
<div data-bind="template: {
name: obj.projectData ? 'nameIfProject' : 'nameIfNoProject' }">
</div>
在我的淘汰赛应用程序中,我有两个可观察数组。一是地点,
self.locations = ko.observableArray([]).withIndex('id');
这包含所有位置。这些位置可以与项目相关联,也可以不相关联。如果项目中不存在位置,则项目 ID 将为空。
另一个数组是项目。它包含所有项目,如果它们有任何位置它有一个位置数组。
现在我要做的是得到一个数组,其中包含两个类似这样的东西
displayLocations = {
location1 = {name = "abc", ...}
... these don't have any projects
location9 = {name = "xyz", projectName = "project1", .. }
}
我正在尝试为此创建一个计算 属性,然后在视图方面,我正在考虑根据位置是否有项目使用不同的模板。
有什么建议吗?
不确定 withIndex
方法,但是使用 vanilla KO 可以在 computed
:
ko.utils.arrayMap
this.associatedLocations = ko.computed(function() {
var dataLoc = this.locations(),
dataProj = this.projects(),
result = ko.utils.arrayMap(dataLoc, function(loc) {
var newObj = loc, project;
if (loc.projectId !== null) {
project = ko.utils.arrayFirst(dataProj, function(proj) {
return proj.id === loc.projectId;
});
newObj.projectData = proj;
}
return newObj;
});
return result;
}, this);
// assumes locations have a 'projectId' & 'name' property, & projects an 'id' property
// will return an array in the form of
// [ {name: 'xyz', projectData: { id: ..., projectName: ...}}]
您可以通过执行以下操作来测试位置是否与项目相关联:
<div data-bind="template: {
name: obj.projectData ? 'nameIfProject' : 'nameIfNoProject' }">
</div>