1

I understand that given an array of objects, I can use _.uniq() to filter out the unique objects by checking against an object property common to each object. I’m wondering, can I check against two properties at once?

For example:

var foo = [
    {"name":"Steve", "age":"56", "car":"Porsche"}, 
    {"name":"Steve", "age":"56", "car":"Mercedes"}, 
    {"name":"Bill", "age":"57", "car":"Porsche"},
    {"name":"Linus", "age":"56", "car":"Mercedes"}
];

var bar = _.unique(foo, false, function(obj, k, v){
    return obj.name && obj.age;
});

console.log(bar);

I was quite hoping I’d get back Steve, Bill and Linus. However, it looks as though only obj.age is being checked against.

4

2 回答 2

6

这个:

return obj.name && obj.age;

方法:

if (!obj.name)
  return obj.name;
return obj.age;

只返回一个值。在您的情况下,由于所有名称都不为空,因此将返回年龄。

如果您想根据姓名和年龄的组合查找唯一的项目,您可以这样做:

return obj.name + "---" + obj.age; // replace "---" with whatever

这将返回一个由名称和年龄组成的字符串。

于 2013-07-25T22:46:36.223 回答
2

迭代器函数旨在作为比较基础。也许不是最好的答案,但不是

return obj.name && obj.age;

尝试

return obj.name + '|' + obj.age;
于 2013-07-25T22:48:35.747 回答