我有两个对象:
ej= {
name="",
code: "",
namebusinessG:"",
codebusinessG:""
};
group = {
name:"",
code:""
}
以及将包含这些对象的两个数组
groupList:any[]=[];
ejList:any[]=[];
我的程序应该像这样工作:
将组添加到 groupList 时:测试 groupList 中是否存在组,如果不存在则添加
将 ej 添加到 ejList 时:测试ejList 中是否存在ej,如果不存在,则添加它。然后程序要在groupList中添加ej.codebusinessG和ej.namebusinessG,但是先验证ej.codebusinessG是否已经存在于groupList.code的列表中,如果不存在则添加。
selectItem(event) {
if (!this.toggle) { // in group
if (this.groupList.length == 0) {
this.groupList.push(event);
} else if (this.testNotExistinginArray(event, this.groupList)) {
this.groupList.push(event);
}
} else { //in ej
if (this.ejList.length == 0) {
this.ejList.push(event);
if (this.groupList.length == 0) {
this.groupList.push({
code: event.codebusinessG,
name: event.nameBusinessG
});
}
} else if (this.testNotExistinginArray(event, this.ejList)) {
this.ejList.push(event);
this.group.code = event.codeBusinessG;
this.group.name = event.nameBusinessG;
if (this.testNotExistinginArray(this.group, this.groupList)) {
this.groupList.push(this.group);
}
}
}
}
这是测试代码是否在数组中的函数:
testNotExistinginArray(event,type) {
let notExist=true;
type.forEach (function(elm) {
if(elm.code === event.code) {
notExist=false
}
})
return notExist;
}
实际行为
添加组时:验证+添加确定
当我添加 ej 时:验证 + 添加OK
但是在第一次和第二次添加ej后,组对应的组添加正确。
但是当我添加第三个 ej 时,ej 被添加到列表中,但相应的组覆盖了 groupList 中的最后一项。
这里有更多细节
当我添加第一个 ej 时。(添加了 ej 和 group)
当我添加第二个( ej 和 group 添加)
然后我第三
codebusinessG 覆盖 groupList 中的最后一个组,而不是在它后面添加。
预期行为
当添加ej
在组列表的最后一个项目后添加ej.codebusinessG + ej.namebusinessG。
有关信息,我正在使用 angular 5 和 Primeng自动完成组件:
<p-autoComplete [(ngModel)]="text" [suggestions]="results" (completeMethod)="search($event)"
emptyMessage={{noBorrowerResult}}
[minLength]="3"
placeholder="Exemple: Apple"
[size] = "40"
field = "name"
[multiple]="true"
>
<ng-template let-elm pTemplate="item">
<div class="suggestion-item">{{elm.name}} ( ID: {{elm.code}} )</div>
</ng-template>
</p-autoComplete>
我已经简化了您的代码,并为您提供了此 stackblitz的示例。
addUniqueObjectToArray(obj, array, criteria, criteriaTwo?) {
if (array.some(g => g[criteria] === obj[criteriaTwo ? criteriaTwo : criteria])) { return; }
array.push(obj);
}
ngOnInit() {
this.addUniqueObjectToArray(this.newGroup, this.groupList, 'code');
this.addUniqueObjectToArray(this.newGroup, this.groupList, 'code');
this.addUniqueObjectToArray(this.ej, this.ejList, 'code');
this.addUniqueObjectToArray(this.ej, this.ejList, 'code');
this.addUniqueObjectToArray(this.ej, this.groupList, 'code', 'codebusinessG');
this.addUniqueObjectToArray(this.ej, this.groupList, 'code', 'codebusinessG');
console.log('Groups : ', this.groupList, ' EJs : ', this.ejList);
}
您现在拥有一个比较两个键的全能函数,并且仅当数组不包含此键时才推入数组。
如果你只传递一个键,它会在这个键上进行比较,否则你可以传递另一个键来改变比较功能。随意在 stackblitz 中尝试它,它就是为此而设计的。
编辑为避免参考问题:
this.addUniqueObjectToArray({code: 'CODE'}, this.ejList, 'code');
const newObj = {code: 'CODE'};
this.addUniqueObjectToArray(newObj, this.ejList, 'code');
为函数提供一个新对象,而不是已经创建的对象。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句