请与属性值'X'的对象是否在JavaScript中数组存在 [英] Check whether an object with property value 'x' exists in an array in Javascript
问题描述
我有很多,我试图从过滤掉重复的对象。当一个对象有一个属性, IMAGEURL
这是present在另一个对象,我想忽略这个对象,继续前进。
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.
我用的NodeJS
此所以如果有我可以用它来使库更容易让我知道。
I'm using nodeJS
for this so if there's a library I can use to make it easier let me know.
我在阵列检查字符串值,做这样的事情以前做过类似的实现:
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?
推荐答案
您可以只使用一个内部循环(跟踪我们是否已经使用看到$ C $见过的循环C>变量 - 实际上,你可以在这里使用的标签,但我发现变量方法更易于阅读):
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):
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]);
}
这篇关于请与属性值'X'的对象是否在JavaScript中数组存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!