我有一个只包含对象的数组,我希望根据它们的一个键值 val.js.url
来移除重复的对象,但希望保留其中最新的那个对象。因此,我在我的代码中使用了 reverse()
。
我的数组:
[
{
"id": "js_1oc3uiteki22",
"tab": {
"title": "title 1",
"url": "http://google.com"
},
"js": {
"initiator": "https://google.com",
"url": "http://url.com"
}
},
{
"id": "js_1oc3uiteki22",
"tab": {
"title": "title 2",
"url": "http://google2.com"
},
"js": {
"initiator": "https://google2.com",
"url": "http://url.com"
}
}
]
期望结果:
[
{
"id": "js_1oc3uiteki22",
"tab": {
"title": "title 2",
"url": "http://google2.com"
},
"js": {
"initiator": "https://google2.com",
"url": "http://url.com"
}
}
]
实际上,我有以下代码可以解决这个问题,但当我需要在同一个js文件中使用该代码2次时,我想这会产生冲突,并且在第二个数组中不能很好地清除重复项。
function dupfix(arr) {
return arr.reverse().filter(val => {
if (!this.hasOwnProperty(val.js.url)) {
return this[val.js.url] = true
}
return false
}, {}).reverse()
}
file = dupfix(file)
那么,我该如何修复上面的代码,或者有没有其他更好的方法?谢谢。
url
是http://url2.com
,而不是原始地址中的http://url.com
?地址中没有数字 2。 - A1exandr Belan