ElementUI下拉多选框OnChange事件,保存的id数组和对象数组的关系
简述:下拉多选框保存的是id数组,而实际上传给后端的是对象数组,这种时候的OnChange方法代码如下
onProgramChanged(detail) {
that = this
curIds = detail
preObjs = this.ledConfs.programList;
// 例如当前的id数组 curIds = [2, 3]
// 之前的对象数组是 preObjs = [{"id": 1, "name": 11}, {"id": 3, "name": 33}, {"id": 5, "name": 55}]
console.log(detail, preObjs)
//1. 添加curIds中的新元素
preIds = preObjs.map(item => { return item.id })
newIds = []
intersectionIds = []
for (const id of curIds) {
if (!preIds.includes(id)) {
newIds.push(id)
} else {
intersectionIds.push(id)
}
}
preObjs = preObjs.filter(item => {
return intersectionIds.includes(item.id)
})
// console.log(that.ledConfs)
for (const id of newIds) {
preObjs.push({ "id": id, "name": that.optionsMap.get(id), "programTimes": 1, "programPriority": 1 })
}
// 排序
preObjs.sort((a, b) => a.id - b.id)
this.ledConfs.programList = preObjs
console.log(preObjs)
},