检查 Javascript 数组中是否存在属性值为“x”的对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18285084/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 11:20:57  来源:igfitidea点击:

Check whether an object with property value 'x' exists in an array in Javascript

javascriptarraysobjectfor-loop

提问by JVG

I have a lot of objects that I'm trying to filter out duplicates from. When an object has a property, IMAGEURLwhich is present in another object, I want to ignore this object and move on.

我有很多对象,我试图从中过滤掉重复项。当一个对象具有IMAGEURL另一个对象中存在的属性时,我想忽略这个对象并继续前进。

I'm using nodeJSfor 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?

我怎样才能做到这一点?

回答by SheetJS

You can just use an inner loop (keeping track of whether we've seen the loop by using a seenvariable -- 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]);
}

回答by bfavaretto

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

Note: this is concise, but orders of magnitude slowerthan Nirk's answer.

注意:这很简洁,但比Nirk's answer几个数量级

See also: http://monkeyandcrow.com/blog/why_javascripts_filter_is_slow/

另见:http: //monkeyandcrow.com/blog/why_javascripts_filter_is_slow/