【问题标题】:How to display unique items and the amount of occurances from an array of objects in Vuejs/JS?如何在 Vuejs/JS 中显示一组对象中的唯一项目和出现次数?
【发布时间】:2021-05-24 23:24:22
【问题描述】:

我正在为这个项目使用 Vuejs 开发库存应用程序,但我的问题特别是与 JS 相关的问题。 在我的数据中,我有用户数据,它是从表单中获取的记录的 userData,然后是您可以从中选择的静态类别和位置。

我正在尝试提取独特的类别以及出现在新对象数组中的次数:

[{title: 'Books', amount: 3 }, {title: 'Recods', amount: 1 }, ...]

我认为我所拥有的是范围问题。

数据

userData: {
        items: [
          {
            itemName: 'test book',
            category: 'Books',
            location: 'Kitchen',
          },
          {
            itemName: 'test book 2',
            category: 'Books',
            location: 'Garage',
          },
          {
            itemName: 'test book 3',
            category: 'Books',
            location: 'Basement',
          },
          {
            itemName: 'test record',
            category: 'Records',
            location: 'Basement',
          },
          {
            itemName: 'test furniture',
            category: 'Furniture',
            location: 'Garage',
          },
        ],
        categories: ['Books', 'Movies', 'Records', 'Furniture'],
        locations: ['Basement', 'Garage', 'Kitchen'],
      },

我正试图让它像我在这里的“书籍”一样工作,但适用于所有类别。 这就是我用下面的代码显示的内容。它显示为“项目:3”,因为我的 userData 中有 3 本书,但我需要它来显示每个唯一类别的数量。 我不知道在下面的代码中放置什么 filteredItems = items.filter((item) => item.category === 'Books').length

方法/功能

   convertedCategories() {
      const items = this.userData.items
      const filteredItems = items.filter((item) => item.category === 'Books').length

      function getItemCountOfCategory(categoryName) {
        return filteredItems
      }
      function convertCategoriesIntoCards(categories) {
        return categories.map((el) => {
          return {
            title: el,
            amount: getItemCountOfCategory(el),
          }
        })
      }
      return convertCategoriesIntoCards(this.userData.categories)
    },

如果我没有将其分解得足够清楚,我深表歉意;我仍然很难从这么多代码中提取出与问题相关的特定行。

如果有什么不清楚的地方,请告诉我!

【问题讨论】:

    标签: javascript vue.js filter array.prototype.map


    【解决方案1】:

    这样的事情应该可以工作。

       convertedCategories() {
          const items = this.userData.items
          function getItemCountOfCategory(categoryName) {
            return items.filter((item) => item.category === categoryName).length
          }
          function convertCategoriesIntoCards(categories) {
            return categories.map((el) => {
              return {
                title: el,
                amount: getItemCountOfCategory(el),
              }
            })
          }
          return convertCategoriesIntoCards(this.userData.categories)
        },
    

    【讨论】:

    • 哇。这确实奏效了!谢谢!所以它只是将我制作的filteredItems变量移动到函数本身,然后用参数代替我上面写的'Books'值?我很高兴我没有完全离开那里,但我想知道是什么让我认为在函数之外定义变量是正确的调用......无论如何,感谢您快速简洁的回复!我不确定我是否正确地提出了这个问题。
    猜你喜欢
    • 2021-05-31
    • 2017-01-15
    • 2015-09-25
    • 1970-01-01
    • 2019-03-31
    • 1970-01-01
    • 2022-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多