数据结构
// 我的频道
myChannel = [{"id":0,"name":"推荐"},{"id":11,"name":"后端"},{"id":12,"name":"linux"},{"id":13,"name":"人工智能"},{"id":17,"name":"前端"},{"id":18,"name":"python"},{"id":7,"name":"数据库"}]
// 所有频道
allChannel = [{"id":2,"name":"开发者资讯"},{"id":3,"name":"ios"},{"id":4,"name":"c++"},{"id":5,"name":"android"},{"id":6,"name":"css"},{"id":8,"name":"区块链"},{"id":9,"name":"go"},{"id":10,"name":"产品"},{"id":11,"name":"后端"},{"id":12,"name":"linux"},{"id":13,"name":"人工智能"},{"id":14,"name":"php"},{"id":15,"name":"javascript"},{"id":16,"name":"架构"},{"id":17,"name":"前端"},{"id":18,"name":"python"},{"id":19,"name":"java"},{"id":20,"name":"算法"},{"id":21,"name":"面试"},{"id":22,"name":"科技动态"},{"id":23,"name":"js"},{"id":24,"name":"设计"},{"id":25,"name":"数码产品"},{"id":1,"name":"html"},{"id":7,"name":"数据库"},{"id":26,"name":"软件测试"},{"id":27,"name":"测试开发"},{"id":31,"name":"test4"},{"id":32,"name":"test18"},{"id":41,"name":"test17"}]
后者包含前者
数据处理要求
将所有频道的数据刨除我的频道的数据获得新的数据,filterChannel = allChannel - myChannel
我写的处理方案
computed: {
filterChannels() {
return this.allChannels.filter((val) => {
for(var i = 0; i < this.myChannel.length; i++) {
if (val.id === this.myChannel[i].id) {
return false
}
}
return true
})
})
}
},
处理方案并不娴熟对array内置的方法没有特别敏感 这里使用Array.prototype.find()会更好
优化后的方案
computed: {
filterChannels() {
// 数组的内置Api
return this.allChannels.filter((val) => {
return !this.myChannels.find((item) => {
return val.id === item.id
})
})
}
},
因为find这个方法他返回的不是Boolean值,如果没找到该元素返回的是undefined,找到了则返回的是改元素的值,如果返回值没有0这种值的话我想这种处理方法有最简洁的代码