javascript - 删除对象数组中的重复元素 Javascript

标签 javascript arrays object filter

基本上我想知道如何清理 JavaScript 中的对象数组。

我已经看到一些示例,这些示例展示了如何根据一个元素的值来执行此操作,并且我需要它是通用的。这意味着它不取决于 child 的名字。

Example of the way i don't want

我需要的是一个可以独立于对象结构工作的函数。

例如,它可以与此一起使用:

object = [
    {value: 'value', configuration: 'configuration'},
    {value: 'value2', configuration: 'configuration2'},
    {value: 'value', configuration: 'configuration'},
]

//returning:

object = {
    {value: 'value', configuration: 'configuration'},
    {value: 'value2', configuration: 'configuration2'}
}

它还可以与:

object = [
    {name: 'name', property: 'property'},
    {name: 'name2', property: 'property2'},
    {name: 'name', property: 'property'},
]

//returning:

object = [
    {name: 'name', property: 'property'},
    {name: 'name2', property: 'property2'}
]

最佳答案

使用filter/findIndex技巧对数组进行重复数据删除非常简单,唯一的问题是我们需要一个相等函数来比较元素。对于对象,简单的 === 不起作用。

这是一个使用基本浅等于比较器的简单示例。它仅检查两个对象是否具有相同键的相同值,这适用于示例中的对象(但不适用于嵌套对象)。根据您的用例,这可能还不够。另一个不错的选择是 lodash 的 _.isEqual 方法,或者比较 JSON 字符串的函数。 重要的是您定义一个函数来比较两个满足您要求的对象

var array1 = [
    {value: 'value', configuration: 'configuration'},
    {value: 'value2', configuration: 'configuration2'},
    {value: 'value', configuration: 'configuration'},
];

var array2 = [
    {name: 'name', property: 'property'},
    {name: 'name2', property: 'property2'},
    {name: 'name', property: 'property'},
];

// You need to define an equality function to use with the deduplicator. Heres a basic one.
function isKVEqual(obj1, obj2) {
  // Get the keys of these objects, make sure they have the same number of keys.
  const o1keys = Object.keys(obj1);
  const o2keys = Object.keys(obj2);
  if (o1keys.length !== o2keys.length) return false;
  
  // Check that the value of each key is the same in each object.
  for (const key of o1keys) {
    if (obj2[key] !== obj1[key]) return false;
  }
  
  return true;
}

// Deduplicate:
// Make sure to replace the isKVEqual call with whatever custom comparator you want to use.
const dedupedArray1 = array1.filter((item, index, list) => list.findIndex(x => isKVEqual(x, item)) === index);
const dedupedArray2 = array2.filter((item, index, list) => list.findIndex(x => isKVEqual(x, item)) === index);

console.log(dedupedArray1)
console.log(dedupedArray2)

关于javascript - 删除对象数组中的重复元素 Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47838135/

相关文章:

javascript - 如何使用 d3 过滤器和更新功能在数据选择之间切换

javascript - 将 JS IIFE 库导出到 React 组件

javascript - 如何制作具有高亮样式的事件菜单项?

javascript - 过滤对象键并创建新的嵌套键

javascript - 在数组中得到错误的输出,javascript

php - 类 stdClass 的对象无法转换为字符串错误

javascript - 遍历具有不同名称的表单字段

c - 在c中切片数组或结构的函数

javascript - 将多维数组转换为单个数组(Javascript)

javascript - 有没有一种方法可以将 JavaScript 对象转换为格式更清晰的另一个对象?