【问题标题】:How can I get all unique tags from an array with lodash?如何使用 lodash 从数组中获取所有唯一标签?
【发布时间】:2020-05-31 06:06:02
【问题描述】:

我正在使用 Vuejs 和 lodash 以及特定的 lodash 来尝试在我的非常简单的问题“应用程序”中获取所有 uniqe 问题标签。但由于某种原因,lodash 会返回所有标签,而不是唯一的标签。这就是我设计问题和标签的方式(可能是更好的方式,但不知道)。

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

【问题讨论】:

    标签: vue.js lodash


    【解决方案1】:

    当您想通过提取来获取单个值数组时 多个数组使用_.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>

    【讨论】:

      【解决方案2】:

      可选,不带 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);

      【讨论】:

        【解决方案3】:

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

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


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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2019-07-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多