从对象数组中删除重复对象的最佳方法是什么?
What's the best way to remove duplicate objects from array of objects?
来自
var arr =
[
{"name":"Joe", "age":17},
{"name":"Bob", "age":17},
{"name":"Carl", "age": 35},
{"name":"Bob", "age":35},
{"name":"Joe", "age":17},
]
删除重复项后,预期的结果是
when duplicates removed, the expected result is
res= arr =
[
{"name":"Joe", "age":17},
{"name":"Bob", "age":17},
{"name":"Carl", "age": 35},
{"name":"Bob", "age":35},
]
(5 个对象,1 个重复,4 个左).
(5 objects, 1 duplicate, 4 left).
每个对象的属性数量是固定的,每个数组的属性名称相同.但是,从一个数组到另一个数组,它们可能不仅仅是上面的名称"和年龄",而是属性的名称可以是任何名称.
The number of properties of each object is fixed, the properties names are the same for each array. However, from array to array they may not be just "name" and "age" as above, but the names of the properties could be any.
@Pointy 请将上述问题中的重复词视为口头意义上的重复" - 对象分别具有相同数量的属性、相同的属性和相同的属性值.
@Pointy Please treat the duplicate word in the question above as 'duplicate' in the verbal sense - the object with the same number of properties, the same properties and the same values of that properties respectively.
这不是重复的 从 JavaScript 数组中删除重复项一个>
你可以使用一个对象来查找,如果一个对象已经被插入或者没有.
You could use an object for lookup, if an object is alreday inserted or not.
更新以获取对象的所有属性并使用键的值.如果只使用一些属性,那么我建议使用带有相关键的数组,例如
Update for getting all properties of the object and use the values for the key. If only some properties should be used for it, then I suggest to use an array with the relavant keys, like
['name', 'age']
并与它一起使用
var key = ['name', 'age'].map(function (k) { return a[k]; }).join('|');
var arr = [{ "name": "Joe", "age": 17 }, { "name": "Bob", "age": 17 }, { "name": "Carl", "age": 35 }, { "name": "Bob", "age": 35 }, { "name": "Joe", "age": 17 }],
filtered = arr.filter(function (a) {
var key = Object.keys(a).map(function (k) { return a[k]; }).join('|');
if (!this[key]) {
return this[key] = true;
}
}, Object.create(null));
console.log(filtered);
这篇关于如何从 JavaScript 数组中删除重复的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
discord.js v12:我如何等待 DM 频道中的消息?discord.js v12: How do I await for messages in a DM channel?(discord.js v12:我如何等待 DM 频道中的消息?)
如何让我的机器人提及发出该机器人命令的人how to make my bot mention the person who gave that bot command(如何让我的机器人提及发出该机器人命令的人)
如何修复必须使用导入来加载 ES 模块 discord.jsHow to fix Must use import to load ES Module discord.js(如何修复必须使用导入来加载 ES 模块 discord.js)
如何列出来自特定服务器的所有成员?How to list all members from a specific server?(如何列出来自特定服务器的所有成员?)
Discord bot:修复“找不到 FFMPEG"Discord bot: Fix ‘FFMPEG not found’(Discord bot:修复“找不到 FFMPEG)
使用 discord.js 加入 discord 服务器时的欢迎消息Welcome message when joining discord Server using discord.js(使用 discord.js 加入 discord 服务器时的欢迎消息)