JavaScript的json数组去重、删重
JavaScript两个json数组删重(使用map+filter)
<template>
<div>两个json数组删重</div>
</template>
<script>
export default {
mounted() {
this.testFn()
},
methods: {
testFn() {
let arr1 = [
{
"id": 1,
"code": "name",
},
{
"id": 2,
"code": "age"
},
{
"id": 3,
"code": "addr"
},
{
"id": 4,
"code": "other"
}
]
let arr2 = [
{
"id": 1,
"code": "name",
},
{
"id": 2,
"code": "age"
},
];
// 调用封装的方法
this.delJson(arr1, arr2, "id");
},
/**
* 两个json数组删重
* @param arr1 数组1
* @param arr2 数组2
* @param attrName 通过哪个属性删重
* @return 删重的结果
*/
delJson(arr1, arr2, attrName) {
let arr = arr2.map(i => i[attrName])
let result = arr1.filter(i => !arr.includes(i[attrName]))
console.log("数组1: ", arr1);
console.log("数组2: ", arr2);
console.log("删重后的结果: ", result);
return result;
}
}
}
</script>
结果
JavaScript一个json数组去重(使用filter)
<template>
<div>1个json数组去重</div>
</template>
<script>
export default {
mounted() {
this.testFn()
},
methods: {
testFn() {
let arr1 = [
{
"id": 1,
"code": "name",
},
{
"id": 2,
"code": "age"
},
{
"id": 1,
"code": "addr"
},
{
"id": 4,
"code": "other"
}
]
// 调用封装的方法
this.uniqueJSON(arr1, "id");
},
/**
* json数组去重
* @param arr 要去重的json数组
* @param attrName 通过哪个属性去重
* @return 去重的结果
*/
uniqueJSON(arr, attrName) {
let result = arr.filter((item, index, self) => {
return index === self.findIndex((t) => (t[attrName] === item[attrName]));
});
console.log("原json数组: ", arr);
console.log("去重结果: ", result);
return result;
}
}
}
</script>
结果
JavaScript一个json数组去重(使用reduce)
<script>
let arr1 = [
{"id": 1, "code": "name"},
{"id": 2, "code": "age"},
{"id": 1, "code": "addr"},
{"id": 4, "code": "other"}
];
// 调用封装的方法
let result = uniqueJSON(arr1, "id");
console.log("原json数组: ", arr1);
console.log("去重结果: ", result);
/**
* json数组去重
* @param arr 要去重的json数组
* @param attrName 通过哪个属性去重
* @return 去重的结果
*/
function uniqueJSON(arr, attrName) {
let obj = {};
let result = arr1.reduce((previousValue, currentValue) => {
(obj[currentValue[attrName]] ? "" : (obj[currentValue[attrName]] = true)) && previousValue.push(currentValue);
return previousValue;
}, []);
return result;
}
</script>
结果
JavaScript找出两个Json数组相同的属性和值(使用reduce)
<script>
/*找出两个Json数组相同的属性和值*/
let arr1 = [
{a: 1},
{a: 2},
{a: 3},
{a: 4},
{a: 5},
];
let arr2 = [
{a: 1},
{a: 3},
{a: 5},
{a: 7},
];
let res = arr1.reduce((accumulator, currentValue) => {
if (arr2.some(element => element.a === currentValue.a)) {
accumulator.push(currentValue);
}
return accumulator;
}, []);
console.log(res); // [{a: 1},{a: 3},{a: 5}]
</script>
结果
JavaScript对象变json数组
<script>
// 用JavaScript将exampleData数据变成exampleRes数据
let exampleData = {
"0:00": {
id: 1
},
"2:00": {
id: 2
},
"4:00": {
id: 3
}
}
let exampleRes = [
{
id: 1,
time: "0:00"
},
{
id: 2,
time: "2:00"
},
{
id: 3,
time: "4:00"
},
];
let res = Object.entries(exampleData).map(element => {
return {
id: element[1].id,
time: element[0]
}
});
console.log(res);
</script>
结果