find方法的理解与使用

在项目中,遇到一个功能,选择多选框,多选框的label为id,要将选择的数据对象反显到表格中。在此使用到find()方法。

find() 方法用于查找数组中符合条件的第一个元素,如果没有符合条件的元素,则返回 undefined。

多选框:

<el-checkbox-group v-model="checkboxdata">
  <el-checkbox v-for="item in checkboxlist" :label="item.id" :key="item.id">{{item.name}}</el-checkbox>
<el-checkbox-group>
checkboxlist:[
    {
        id:"1",
        name:"名称1"
    },
    {
        id:"2",
        name:"名称2"
    }
],
checkboxdata:["1"],

tabledata:[]
 

表格:

<el-table :data="tabledata">
  <el-table-column label="名称" prop="name"></el-table-column>
</el-table>

将选择的多选框的内容显示到表格中,即查找到id符合的对象,且对象的名称name与表格的名称name为相同字段。

首先要循环被选择的多选框数据,即被选择数据的id集合:

this.checkboxdata.forEach(item=>{})

需要查找checkboxlist中checkboxdata循环的id对应的对象

this.checkboxlist.find(x=>{return x.id = 循环的id })

将查找到的对象插入到表格数组中,使用push()方法。完整的实现代码为:

this.checkboxdata.forEach(item=>{
 this.tabledata.push(this.checkboxlist.find(x=>{
  return x.id = item
  }))
})

若选中的为名称1,则checkboxdata为["1"],经过循环,查找出checkboxlist中id为1的对象为{id:"1",name:"名称1"},于是将此对象插入到表格中,即完成回显。

posted @ 2022-03-09 19:15  zwbsoft  阅读(274)  评论(0)    收藏  举报