[英]Check whether an object with property value 'x' exists in an array in Javascript
I have a lot of objects that I'm trying to filter out duplicates from. 我有很多对象,我试图从中删除重复项。 When an object has a property,
IMAGEURL
which is present in another object, I want to ignore this object and move on. 当一个对象有一个属性,
IMAGEURL
出现在另一个对象中时,我想忽略这个对象并继续前进。
I'm using nodeJS
for this so if there's a library I can use to make it easier let me know. 我正在使用
nodeJS
,所以如果有一个库我可以用来让它更容易让我知道。
I've done similar implementations before with checking string values in arrays, doing something like: 在检查数组中的字符串值之前,我已经完成了类似的实现,执行如下操作:
var arr = ['foo', 'bar'];
if(arr.indexOf('foo') == -1){
arr.push('foo')
}
But this won't work for objects, as best I can tell. 但是这对于对象来说是行不通的,正如我所知道的那样。 What are my options here?
我有什么选择? To put it more simply:
更简单地说:
var obj1 = {IMAGEURL: 'http://whatever.com/1'};
var obj2 = {IMAGEURL: 'http://whatever.com/2'};
var obj3 = {IMAGEURL: 'http://whatever.com/1'};
var arr = [obj1, obj2, obj3];
var uniqueArr = [];
for (var i = 0; i<arr.length; i++){
// For all the iterations of 'uniqueArr', if uniqueArr[interation].IMAGEURL == arr[i].IMAGEURL, don't add arr[i] to uniqueArr
}
How can I do this? 我怎样才能做到这一点?
You can just use an inner loop (keeping track of whether we've seen the loop by using a seen
variable -- you can actually use labels here, but I find the variable method to be easier to read): 你可以使用一个内循环(跟踪我们是否通过使用一个
seen
变量看到了循环 - 你实际上可以在这里使用标签,但我发现变量方法更容易阅读):
for (var i = 0; i<arr.length; i++){
var seen = false;
for(var j = 0; j != uniqueArr.length; ++j) {
if(uniqueArr[j].IMAGEURL == arr[i].IMAGEURL) seen = true;
}
if(!seen) uniqueArr.push(arr[i]);
}
Here is a concise way: 这是一个简洁的方法:
var uniqueArr = arr.filter(function(obj){
if(obj.IMAGEURL in this) return false;
return this[obj.IMAGEURL] = true;
}, {});
http://jsfiddle.net/rneTR/2 http://jsfiddle.net/rneTR/2
See also: http://monkeyandcrow.com/blog/why_javascripts_filter_is_slow/ 另见: http : //monkeyandcrow.com/blog/why_javascripts_filter_is_slow/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.