打字稿数组 - 拼接&插入

时间:2018-01-02 19:46:52

标签: arrays angular typescript

我这里有3个类型为channel array的数组。

currentPickSelection: Array<channel>;
draggedChannel: channel;
droppedChannel: channel;

我要做的是从currentPickSelection数组中删除一个项目(droppedChannel数组项目),并将draggedChannel项目数组插入到已删除项目的相同索引中。 这是我到目前为止所做的,除插入部分外,一切正常:

 let index = this.currentPickSelection.findIndex(item => item === this.droppedChannel);
 this.currentPickSelection.splice(index, 1, this.draggedChannel);

这是我声明通道模型的方式:

export class CompChannel {
    constructor(public compChannelCbsCode: string, 
        public compChannelName: string, 
        public compChannelLogo: string) {}
}

export class channel {
    public pickCode: string;
    public cbsCode: string;
    public channel: string;
    public logo: string;
    public compChannel: CompChannel[];

    constructor(pickCode: string, cbsCode: string, channel: string,
        logo: string, compChannel: CompChannel[]) {
        this.pickCode = pickCode;
        this.cbsCode = cbsCode;
        this.channel = channel;
        this.logo = logo;
        this.compChannel = compChannel;
    }
}

请告知错误!

1 个答案:

答案 0 :(得分:0)

droppedChannel对象和currentPickSelection中找到的项目可能不是彼此的确切相同副本/克隆

尝试与pickCode方法中的唯一值(例如cbsCodefindIndex)进行比较,而不是与整个对象进行比较。

let currentPickSelection: any[] = [
 { id: 1, label: 'Test1' },
 { id: 2, label: 'Test2' },
 { id: 3, label: 'Test3' }
];
let draggedChannel: any = { id: 5, label: 'Test5' };
let droppedChannel: any = { id: 3, label: 'Test3' };
let index = currentPickSelection.findIndex(item => {
   return item.id == droppedChannel.id; //use unique value instead of item object
});
if (index > -1) 
 currentPickSelection.splice(index, 1, draggedChannel);