JavaScript 实现数组对象差集对比与替换逻辑
作者:木棉时间:2026-10-30 22:31:14浏览:426
本文介绍在JavaScript中获取两个数组对象差集的方法。核心思路是将数组转换为以parentId为键、childId为值的对象以便对比,进而找出存在差集的项目并将其替换。文中包含基于Vue和Element UI的完整示例代码,展示了具体的实现逻辑与数据处理流程。
本文旨在说明如何提取两个数组对象中互不包含的元素部分。

所谓获取两个数组对象的差集,即找出在对比过程中未被共同包含的元素集合:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>获得两个数组对象的差集</title>
<!--引入 element-ui 的样式,-->
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css" rel="external nofollow" >
<script src="https://cdn.bootcss.com/vue/2.5.16/vue.min.js"></script>
<!-- 引入element 的组件库-->
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<style>
* {
margin: 0;
padding: 0;
}
#app {
margin: 50px;
}
.item {
margin-bottom: 20px;
}
</style>
</head>
<body>
<div id="app">
<div class="item">
原数组:
<div v-for="(item, index) in selectedText" :key="index">{{item}}</div>
</div>
<div class="item">
和原数组对比的数组:
<div v-for="(item, index) in brightTextArr" :key="index">{{item}}</div>
</div>
<div class="item">
差集:
<div v-for="(item, index) in differenceSet" :key="index">{{item}}</div>
</div>
</div>
<script>
new Vue({
el: '#app',
data() {
return {
// 原数组
selectedText: [
{
"parentId": "1665538708874002433",
"childId": [
"0",
"1",
"2",
"3",
"4",
"5",
"6",
"7"
]
},
{
"parentId": "1665538708861419522",
"childId": [
"0",
"1",
"2",
"3",
"4",
"5"
]
}
],
// 要对比的数组
brightTextArr: [
{
"parentId": "1665538708861419522",
"childId": [
"3",
"4",
"5",
'9'
]
},
{
"parentId": "1665538708869808130",
"childId": [
"0",
"1",
"2",
"3",
"4",
"5",
"6",
"7"
]
}
],
// 差集
differenceSet: []
}
},
created() {
this.subtractionFun(this.selectedText, this.brightTextArr)
},
methods: {
subtractionFun(selectedText, brightTextArr) {
this.differenceSet = JSON.parse(JSON.stringify(brightTextArr));
// 转换成对象,parentId为属性名,childId为属性值,
// 格式为 { 1665538708861419522: ['3', '4', '5', '9'] }
const brightTextMap = this.differenceSet.reduce((pre, cur) => {
return {
...pre,
[cur.parentId]: cur.childId,
};
}, {});
selectedText.forEach((item, index) => {
const childId = item.childId || [];
const parentChildId = brightTextMap[item.parentId] || [];
// 求两个数组的差集
const subtraction = parentChildId.filter((v) => !childId.includes(v));
const parentChildIdIndex = this.differenceSet.findIndex(
(v) => v.parentId === item.parentId
);
if (parentChildIdIndex >= 0) {
// 找到和原数组有相同有parentId并且有差集的那一项,替换成差集
this.differenceSet[parentChildIdIndex].childId = subtraction;
}
});
console.log(this.differenceSet, '差集')
},
}
})
</script>
</body>
</html>具体应用场景与问题背景
第一步,需将待对比的数组对象转换为以 parentId 为属性名、childId 为属性值的对象结构,这种格式便于后续进行对比操作。
转换后的数据格式示例如下:{ 1665538708861419522: ['3', '4', '5', '9'] }
第二步,需要定位那些与原数组拥有相同 parentId 但存在差集的项目,并将这些项目替换为计算出的差集内容。
以上即为 JavaScript 获取两个数组对象差集的具体实现方法,更多关于该主题的资料可参考本站其他相关文章。
作者最新文章
JS运算符优先级与结合性的区别是什么?
2026-11-05 13:22:02
JS Map怎么只遍历Key或Value
2026-11-05 13:00:36
D3.js 与 ECharts 选型对比:灵活性 vs 开发效率
2026-11-05 09:45:01
为什么JS中typeof []返回object:数组类型检测误区解析
2026-11-04 19:50:47
D3.js 新手入门:环境搭建与第一个条形图实现
2026-11-04 10:49:48
