如何使用 lodash 从数组中获取所有唯一标签?



我使用 Vuejs 和 lodash 以及特定的 lodash 来尝试在我非常简单的问题"app"中获取所有 uniqe 标签。但出于某种原因,lodash 会恢复所有标签,而不是 uniqe 标签。这就是我设计问题和标签数组的方式(可能是一种更好的方法,但不知道(。

created() {
this.tags = _.chain(this.fragor).map('tags').uniq().value()
},
data: function() {
return {
tags:[],
fragor:[
{
'fraga': "Question 1",
'svar' : "This is this explanation",
'tags' : ['knowledge'],
},
{
'fraga': "Question 2",
'svar' : "This is this explanation for question 2",
'tags' : ['knowledge', 'code'],
},
{
'fraga': "Question 3",
'svar' : "This is this explanation for question 3",
'tags' : ['code'],
}
]
}
}

tags是返回[ "knowledge" ] [ "knowledge", "code" ] [ "code" ]何时应['knowledge', 'code']预期结果。我怎样才能用 lodash 和 vue 来实现这一点?

我为你们做了一个jsfiddle。

当您想通过提取来获取单个值数组时 多个数组使用_.flatMap()

const fragor = [{"fraga":"Question 1","svar":"This is this explanation","tags":["knowledge"]},{"fraga":"Question 2","svar":"This is this explanation for question 2","tags":["knowledge","code"]},{"fraga":"Question 3","svar":"This is this explanation for question 3","tags":["code"]}]
const tags = _(fragor).flatMap('tags').uniq().value()
console.log(tags)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

可选,不带 lodash:

const fragor = [{ fraga: 'Question 1', svar: 'This is this explanation', tags: ['knowledge'] }, { fraga: 'Question 2', svar: 'This is this explanation for question 2', tags: ['knowledge', 'code'] }, { fraga: 'Question 3', svar: 'This is this explanation for question 3', tags: ['code'] }];
const tags = Array.from(new Set(fragor.map(f => f.tags).flat()));
console.log(tags);

uniq()是一个lodash方法,而不是数组上的方法。


_(this.fragor).map('tags').uniq().value()

你的方式是错误的,因为 lodash 不会修改原型。希望这可能会有所帮助。

最新更新