Min*_*Vox 16 javascript node.js lodash
我有一个lodash变量;
var usernames = _.map(data, 'usernames');
Run Code Online (Sandbox Code Playgroud)
产生以下内容;
[
"joebloggs",
"joebloggs",
"simongarfunkel",
"chrispine",
"billgates",
"billgates"
]
Run Code Online (Sandbox Code Playgroud)
我怎么能调整lodash语句,以便它只返回一个唯一值数组?例如
var username = _.map(data, 'usernames').uniq();
Run Code Online (Sandbox Code Playgroud)
Dav*_*ton 50
很多方法,但uniq()不是数组上的方法,它是一种lodash方法.
_.uniq(_.map(data, 'usernames'))
Run Code Online (Sandbox Code Playgroud)
要么:
_.chain(data).map('usernames').uniq().value()
Run Code Online (Sandbox Code Playgroud)
(第二个是未经测试的,可能是错误的,但它很接近.)
正如评论中所提到的,根据你的数据实际是什么,你可以一次性完成所有这一切,而无需先拔出任何东西usernames.
Ale*_*Trn 11
您还可以使用uniqBy函数,该函数还接受为数组中的每个元素调用的 iteratee。它接受如下两个参数,其中id是 iteratee 参数。
_.uniqBy(array, 'id')
Run Code Online (Sandbox Code Playgroud)