JSON数组去重
/*
* JSON数组去重
* @param: [array] json Array
* @param: [string] 唯一的key名,根据此键名进行去重
*/
const uniqueArray = (array, key) => {
if (array.length > 0) {
var result = [array[0]];
for (var i = 1; i < array.length; i++) {
var item = array[i];
var repeat = false;
for (var j = 0; j < result.length; j++) {
if (item[key] == result[j][key]) {
repeat = true;
break;
}
}
if (!repeat) {
result.push(item);
}
}
return result;
} else {
return array;
}
}
调用
let arr = [{userName: '张三',userID: 3},{userName: '张三',userID: 3},{userName: '李四',userID: 4}];
console.log(uniqueArray(arr, 'userID'));
按key值分割显示
const formatterList2Str = (arr, ckey, split = ',') => {
if (arr && arr.length > 0) {
return arr.map(v => v[ckey]).join(split);
}
return "";
}
let arr = [{userName: '张三',userID: 3},{userName: '李四',userID: 4}];
console.log(formatterList2Str(arr, 'userName')); // 张三,李四
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)