javascript - 使用 JS 从动态多级嵌套对象中删除重复项
问题描述
我有嵌套的 json 对象,我需要删除具有重复键的对象。例如:在给定的数组中,我需要根据“value”键从编辑、新建和删除中删除重复项。我尝试了多种方法,但我无法动态地做到这一点。
let json = {
edit:{
params:[],
items:[
{
id:"1",
source:"text",
value:"new1"
},
]
},
delete:{
params:[],
items:[
{
id:"2",
source:"text",
value:"new2"
},
]
},
new:{
params:[],
items:[
{
id:"3",
source:"text",
value:"new1"
},
{
id:"4",
source:"text",
value:"new"
},
{
id:"5",
source:"text",
value:"new2"
},
{
id:"6",
source:"text",
value:"new"
},
]
},
text:{
name:"test",
value:"test",
id:"10"
}
}
预期输出应该是:
let result = {
edit:{
params:[],
items:[
{
id:"1",
source:"text",
value:"new1"
}
]
},
delete:{
params:[],
items:[
{
id:"2",
source:"text",
value:"new2"
}
]
},
new:{
params:[],
items:[
{
id:"4",
source:"text",
value:"new"
}
]
},
text:{
name:"test",
value:"test",
id:"10"
}
}
解决方案
一种简单的方法是让一个数组在遍历项目时保存所有解析的值,并根据它们在该数组中的包含来过滤项目:
// Create empty array of values to use to check for duplicates
const values = [];
// Create empty result object
const result = {};
// Loop through the edit, delete, new and text keys from the json
Object.keys(json).forEach(key => {
const obj = json[key];
// Loop through items and filter out non-duplicates
const items = obj.items.filter(item => !values.includes(item.value));
// Store the items values in the duplicate check array
items.forEach(item => values.push(item.value));
// Add the key to the results
result[key] = {
...obj, // Spread all values from the original obj
items, // Overwrite the items
};
});
推荐阅读
- ansible - 关于将 apt_repository 与 Ansible 一起使用的问题
- macos - Big Sur react native 如何让守望者跑起来?
- javascript - 在 Monorepo 中的模块之间共享一个 ES6 模块
- java - 仅使用一个 Media Payer 实例在 android 中播放多个音频文件
- scala - Presto 出现此错误:无法调用“com.fasterxml.jackson.databind.JsonNode.has(String)”,因为“currentNode”为空
- yarnpkg - `yarn semantic-release-cli setup` 失败,来自 github 授权 API 的 404
- python - 使用 Spacy 中的自定义标记器对没有空格的字符串进行标记
- html - 导航元素未对齐
- c++ - C++ 复制构造函数错误地接受参数
- excel - 将 8 个工作簿导入一个工作簿,每个工作簿都有自己的工作表