How to remove duplicated OBJECTS from JavaScript array?(如何从 JavaScript 数组中删除重复的对象?)
问题描述
从对象数组中删除重复对象的最佳方法是什么?
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 数组中删除重复的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何从 JavaScript 数组中删除重复的对象?


- 400或500级别的HTTP响应 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- Fetch API 如何获取响应体? 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07