基本上我想知道如何清理 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/