Compare two different arrays of js in vue+elementui, find out different items and put them into the new array.

Foreground:
In the project, two different arrays need to be compared, and the different items are put into the new array.

insert image description here
Example:
Each user has an independent account.
Encountered in the project: the premise is that the user has been manually selected before, and the user name permission of this operation user has been manually canceled in the background, and the user item of dragon beard noodle can actually be submitted. (However, this Longxumian user will not be displayed in the actual drop-down box list. There will be Longxumian users in the selected item, which have been selected before).

Example:
(dynamically returned list)
a array: a list of selected items in the drop-down box

let a=ref([
{userName:'黄金糕',userId:'1'},
{userName:'双皮奶',userId:'2'},
{userName:'蚵仔煎',userId:'3'},
{userName:'龙须面',userId:'4'},
])

(dynamically returned list)
b array: regardless of whether there is a selected item in the drop-down box, it will be displayed (all items in the drop-down box)

let b=ref([
{nickName:'黄金糕',userId:'1'},
{nickName:'北京烤鸭',userId:'5'},
])
let editOptions=ref([]);//新数组

html

//弹出框的新增和修改公用一个下拉列表项
//其他代码段省略..
//重要部分
//keyIds:【1,2,3,4】选中项返回的数组list
//v-show="!item.tag"  控制当前项不为真就不显示下拉列表项当前name
<el-form>
<el-form-item label="名称: " prop="keyIds">
  <el-select v-model="form.coop" multiple  placeholder="请选择">
  //editOptions是组成的新数组
    <el-option
      v-for="item in editOptions"
      :key="item.userId"
      :label="item.nickName"
      :value="item.userId" v-show="!item.tag">
      <span>{
   
   { item.nickName }}</span>
     </el-option>
   </el-select>
  </el-form-item>
  </el-form>

js

//data.a 是后台返回的数组 list
//data.a为空的时候是null 
//所以用三元运算符解决
  data.a ? true : data.a = []
      let arr = []
      let idList = []
      b.value.forEach(i => {
        idList.push(i.userId)
      })
      data.a.forEach(item => {
        if (idList.indexOf(item.userId) === -1) {
          arr.push({
            nickName: item.userName,
            userId: item.userId,
            tag: true
          })
        }
      })
      nextTick(() => {
      //editOptions 组成一个新数组 
        editOptions.value = [...b.value, ...arr]
        console.log('修改名称',editOptions.value);
      })

Guess you like

Origin blog.csdn.net/weixin_46409887/article/details/129182882