Lodash地图并返回唯一 [英] Lodash map and return unique

查看:63
本文介绍了Lodash地图并返回唯一的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个lodash变量;

I have a lodash variable;

var usernames = _.map(data, 'usernames');

产生以下内容;

[
    "joebloggs",
    "joebloggs",
    "simongarfunkel",
    "chrispine",
    "billgates",
    "billgates"
]

如何调整lodash语句,使其仅返回唯一值数组?例如

How could I adjust the lodash statement so that it only returns an array of unique values? e.g.

var username = _.map(data, 'usernames').uniq();

推荐答案

很多方法,但是uniq()不是数组上的方法,而是lodash方法.

Many ways, but uniq() isn't a method on array, it's a lodash method.

_.uniq(_.map(data, 'usernames'))

或者:

_.chain(data).map('usernames').uniq().value()

(第二个未经测试,可能有误,但是已经接近了.)

(The second is untested and possibly wrong, but it's close.)

如评论中所述,根据数据实际是什么,您可以一次完成所有操作,而无需先提取usernames是什么.

As mentioned in the comment, depending on what your data actually is, you could do this all in one shot without first pulling out whatever usernames is.

这篇关于Lodash地图并返回唯一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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