当我选择一个对象字段时,为什么lodash的_.unique不返回唯一对象? [英] Why isn't lodash's _.unique returning unique objects when I pluck a field that is an object?

查看:76
本文介绍了当我选择一个对象字段时,为什么lodash的_.unique不返回唯一对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用lodash的 _.unique ,它无法正常工作.我正在这样做:

I'm using lodash's _.unique and it's not working as expected. I'm doing this:

uniqueByFocusIndex = _.unique(clickables, false, "focusIndex");

如您在图像中所见(如右图所示),它返回两个具有相同focusIndex es值的元素.我希望这能返回两者之一,而不是两者都返回.是因为_.unique仅适用于基本类型而不适用于对象吗?

And as you can see in the image (look at the right), it's returning two elements with the same values for their focusIndexes. I'd expect this to return one of the two, not both. Is it because _.unique only works on primitives and not objects?

点击展开:

推荐答案

它不起作用,因为比较对象是通过引用完成的,即使对象内容相同也返回false.

It doesn't work because comparing objects is done by reference and returns false even if the objects' contents are the same.

使用字符串作为回调将使用pluck回调样式来检查这些值,但是在该键下拥有的那些对象的比较将始终为false.

Using a string for the callback will check those values using the pluck callback style, but comparison of those objects you have under that key will always be false.

我试图找到一种方法来进行其他一些回调,但是我认为您最好编写自己的适合自己用途的uniq函数.

I tried to find a way to do this with some other callback, but I think you would be better off just writing your own uniq function that fits your purposes.

这篇关于当我选择一个对象字段时,为什么lodash的_.unique不返回唯一对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆