我正在尝试实现一种功能,以使用打字稿从一个项目中选择多个项目并添加/删除另一个项目。
//data of the display list, each element has same value for text & value.
private listA: any = {};
private listB: any = {};
//string array contains the list of name selected
private selectA: string[] = [];
private selectB: string[] = [];
private addClick: void {
//remove all from listA that match name found in selectA
//add to listB all name found in selectA
}
我将如何实现此功能?我已经设法获取数据(listA
和listB
)来填充我的列表,所以这不是问题,我的问题是为数据正确准备数据。
我是打字机和javascript的新手,所以语法现在是造成问题的原因。我尝试使用Object.assign()
,删除和我发现的其他几个功能,但到目前为止还算不上成功。
答案 0 :(得分:1)
这是您要找的吗?
// data of the display list, each element has same value for text & value.
private listA: any[] = [];
private listB: any[] = [];
// string array contains the list of name selected
private selectA: string[] = [];
private selectB: string[] = [];
private addClick(): void {
// Get items from listA that match selectA.
const matching = this.listA.filter(x => this.selectA.includes(x.value));
// Filter listA to only include items that are not a match from selectA.
this.listA = this.listA.filter(x => !this.selectA.includes(x.value));
// Add matching items from listA to listB.
this.listB.push(matching);
}
this.listB.push(matching)
将元素追加到数组的末尾。您还可以使用this.listB.unshift(matching)
将它们放在开头。
答案 1 :(得分:1)
我不确定我是否100%理解您的问题,但是我尝试了此操作,并且似乎可以对其进行检查,我们可以对其进行修改,直到达到您的要求
class Test { //data of the display list, each element has same value for text & value.
private listA: any = {a:'a','b':'b'};
private listB: any = {};
//string array contains the list of name selected
private selectA: string[] = ['a','b'];
private selectB: string[] = [];
public addClick(): void {
this.selectA.forEach((item) => {
if (this.listA[item]) {
this.listB[item] = item;
delete this.listA[item];
}
})
}
public showResult(){
console.log('ListA',this.listA)
console.log('SelectA',this.selectA)
console.log('ListB',this.listB)
}
//remove all from listA that match name found in selectA
//add to listB all name found in selectA
}
然后我们可以运行
let test = new Test();
test.showResult();
test.addClick();
test.showResult();
结果将符合预期
ListA { a: 'a', b: 'b' }
SelectA [ 'a', 'b' ]
ListB {}
ListA {}
SelectA [ 'a', 'b' ]
ListB { a: 'a', b: 'b' }
答案 2 :(得分:0)
步骤
注意:-splice()方法将改变原始列表;如果您不想更改列表,可以使用filter()方法