gpt4 book ai didi

javascript - 在数组中查找重复对象并标记这些 [Javascript lodash]

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:00:40 24 4
gpt4 key购买 nike

我有一个包含对象的数组:

var test = [
{
type: "home",
name: "My home",
country: "DE",
postalZone: "1234",
cityName: "GermanCity"
},
{
type: "home",
name: "Some one else home",
country: "DE",
postalZone: "1234",
cityName: "GermanCity"
},
{
type: "home",
name: "My home",
country: "DE",
postalZone: "1234",
cityName: "GermanCity"
},
{
type: "home1",
name: "My home",
country: "DE",
postalZone: "1234",
cityName: "GermanCity"
},
{
type: "home",
name: "My home",
country: "DE",
postalZone: "1234",
cityName: "GermanCity"
}
];

我想标记它们是重复的对象,像这样(注意额外的属性,isDuplicate):

var test = [
{
type: "home",
name: "My home",
country: "DE",
postalZone: "1234",
cityName: "GermanCity"
},
{
type: "home",
name: "Some one else home",
country: "DE",
postalZone: "1234",
cityName: "GermanCity"
},
{
type: "home",
name: "My home",
country: "DE",
postalZone: "1234",
cityName: "GermanCity",
isDuplicate: true
},
{
type: "home1",
name: "My home",
country: "DE",
postalZone: "1234",
cityName: "GermanCity"
},
{
type: "home",
name: "My home",
country: "DE",
postalZone: "1234",
cityName: "GermanCity",
isDuplicate: true
}
];

如果上述值之一发生变化(type、name、country、postalZone 或 cityName),则该对象是唯一的。

出于测试目的,我尝试了以下方法。仅获取“类型”的唯一对象对我不起作用,例如

_.uniq(test, "type");

还是得到所有的数组对象。当然,我想检查更多对象键,不仅是类型,还有所有对象键(类型、名称、国家/地区、postalZone 或 cityName)。

原生数组函数“some”,如果找到第一个重复项就停止,对我来说它不应该停止...

我怎样才能做到这一点?

我有 Lodash v4.13.1。

最佳答案

这是一个使用 map() 来更改对象的解决方案,如果它被发现是重复的,并且为了找到重复项,我使用了 find()isEqual()。因此,如果找到重复项,它将添加属性,如果没有,它将只返回对象。

var test = [{
type: "home",
name: "My home",
country: "DE",
postalZone: "1234",
cityName: "GermanCity"
}, {
type: "home",
name: "Some one else home",
country: "DE",
postalZone: "1234",
cityName: "GermanCity"
}, {
type: "home",
name: "My home",
country: "DE",
postalZone: "1234",
cityName: "GermanCity"
}, {
type: "home1",
name: "My home",
country: "DE",
postalZone: "1234",
cityName: "GermanCity"
}, {
type: "home",
name: "My home",
country: "DE",
postalZone: "1234",
cityName: "GermanCity"
}];


var result = _.map(test, function(o, i) {
var eq = _.find(test, function(e, ind) {
if (i > ind) {
return _.isEqual(e, o);
}
})
if (eq) {
o.isDuplicate = true;
return o;
} else {
return o;
}
})

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>

关于javascript - 在数组中查找重复对象并标记这些 [Javascript lodash],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39529882/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com