目标:
1、对下面List仅仅取某个字段,并且重新封装成新List。
2、对新的List去重操作
数据源:
[
{
"crjGuid": "2747e837-9481-42d0-91d9-9c079f4ba6af",
"gdGuid": "494f6935-c5a8-4d8d-825a-fb4413da271a",
"zfQh": 1,
"zfSj": "2021-01-13T16:00:00.000+0000",
"bz": null,
"isBght": null,
"zfJe": 1111,
"ydzfqhStr": "第1期",
"dzBaBh": "3301272021B000118",
"ydzfjeStr": "1111.000000万元",
"sjzfJe": null,
"znJe": null,
"lxJe": null,
"sjzfQh": null
},
{
"crjGuid": "1212",
"gdGuid": "494f6935-c5a8-4d8d-825a-fb4413da271a",
"zfQh": 2,
"zfSj": "2021-03-24T07:10:45.000+0000",
"bz": null,
"isBght": null,
"zfJe": 11,
"ydzfqhStr": "第2期",
"dzBaBh": "3301272021B000118",
"ydzfjeStr": "11.000000万元",
"sjzfJe": null,
"znJe": null,
"lxJe": null,
"sjzfQh": null
}
]
方法:
/**
*
* @param array 需要去重的数组
* @param filterKey 去重依据字段
* @returns {Array} 去重后的数字
* @例子 var arr = unique(array, 'bpGuid');
*/
function unique(array, filterKey) {
var fca = [];
var newArr = [];
if (!Array.isArray(array)) {
console.log('type error!')
return;
}
fca = arrset(array, [filterKey], false);
// 去重
fca = Array.from(new Set(fca));
// 符合去重条件的key,重新封装数组内容
fca.forEach(fcaDt => {
var result = array.find(e => {
return e[filterKey] === fcaDt;
});
newArr.push(result);
})
return newArr;
}
/**
* 重新封装数组
* @param array 数组
* @param cols 需要重新封装的字段(List)
* @param kv 是否显示kv结构 true or false
* @returns [1, 2]/ [ {jzfQhStr: "1",sex:"1"},{jzfQhStr: "2",sex:"0"}]
* @demo arrset(this.tdZjdJtXzTable, ['bpGuid'],false) or arrset(this.tdZjdJtXzTable, ['bpGuid','bh'],true)
*/
function arrset(array, cols, kv) {
let newArr = [];
array.forEach(e => {
var obj = {};
cols.forEach(c => {
const data = e[c];
if (kv) {
obj[c] = data;
} else {
newArr.push(data);
}
// console.info('kv为true对象',obj);
})
if (kv) {
newArr.push(obj);
}
});
return newArr;
}
前端代码部分:
// 2021/3/12 xuhy 筛选所有合同(v-for click 跳转需要 gdGuid isBight dzBaBh)
var zfyds = ArrayOption().arrset(resp.data.tCrjZfydList, ['gdGuid','isBight','dzBaBh'], true);
var unique_zfyds = ArrayOption().unique(zfyds , 'gdGuid');
this.List = unique_zfyds;
结果截图: