首页 > 解决方案 > 使用 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"
  }
}

标签: javascriptnested-object

解决方案


一种简单的方法是让一个数组在遍历项目时保存所有解析的值,并根据它们在该数组中的包含来过滤项目:

// 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
  };
});

推荐阅读