Vue 比较两个数组对象,页面展示差异数据值
需求:
页面要展示出被删除和添加的数据,知道哪些被删除和新添加的数据!如下图:
实现:
Vue 中使用 Lodash 的 differenceBy 函数可以方便地比较两个数组并找出它们的差异。
安装和引入Lodash
首先,你需要在项目中安装Lodash库。可以通过npm进行安装:
npm i --save lodash
然后,在需要使用differenceBy函数的组件中引入Lodash:
import _ from 'lodash';
使用differenceBy函数
differenceBy
函数用于找出第一个数组中存在而第二个数组中不存在的元素。其基本语法如下:
_.differenceBy(array, [arrays], [iteratee])
array
:要检查其元素的数组。[arrays]
:(可选)一个或多个数组。[iteratee]
:(可选)每次调用返回一个用于比较的值。
示例代码
假设有两个数组beforeCities
和afterCities
,你想找出beforeCities
中有而afterCities
中没有的元素:
import _ from 'lodash';const beforeCities: [{value: 'Beijing',label: '北京'}, {value: 'Shanghai',label: '上海'}, {value: 'Nanjing',label: '南京'}],const afterCities: [{value: 'Beijing',label: '北京'}, {value: 'Nanjing',label: '南京'}, {value: 'Chengdu',label: '成都'}, {value: 'Shenzhen',label: '深圳'}, {value: 'Guangzhou',label: '广州'}],const result = _.differenceBy(beforeCities, afterCities, 'value');
console.log(result); // 输出: [{value: 'Shanghai',label: '上海'}]
进阶:
进一步封装函数,分别得到删除和添加的数据
<div class="box-left"><h1>城市(选择前)</h1><d-table :data="beforeData"></d-table></div><div class="box-warp"><div class="box-top"><h1>被删除的城市</h1><d-table :data="initData .del"></d-table></div><div class="box-bottom"><h1>新增加的城市</h1><d-table :data="initData .add"></d-table></div></div><div class="box-right"><h1>城市(选择后)</h1><d-table :data="afterData"></d-table></div>initData : {add:[], del:[]}import { Dtable} from '@/components/Dtable'created() {this.initData = this.handList(this.beforeData, this.afterData)},methods: {handList(arr1, arr2) {var del= _.differenceBy(this.setJson(arr1), this.setJson(arr2), 'json')var add = _.differenceBy(this.setJson(arr2), this.setJson(arr1), 'json')return {add,del,}},setJson(arr) {arr.forEach(i => {i.json = JSON.stringify(i)});return arr;}}