【问题标题】:How to place these 2 arrays inside separate objects and push to the main array in JS?如何将这两个数组放在单独的对象中并推送到 JS 中的主数组?
【发布时间】:2021-01-11 01:24:32
【问题描述】:

我有 2 个过滤后的数组:

productsByCategory,
productsByTag

所以我需要得到以下结构:

this.filteredProducts = [{
  type: 'Category'
  products: productsByCategory // it's array
}, {
  type: 'Tag'
  products: productsByTag // it's array
}]

所以这应该是最终结果。我正在使用 Vue.js 和 lodash。如何以优雅的方式实现这一点?

【问题讨论】:

  • 按照您已经输入的方式创建结构。
  • 正如 Ori Drori 所说,您已经编写了需要编写的代码。

标签: javascript vue.js vuejs2 lodash underscore.js


【解决方案1】:

如果您说出该结构背后的意图,则可以给出一个很好的直截了当的答案,否则您可以使用一种方法来完成它。

{
  data() {
    return {
      productsByCategory: [],
      productsByTag: [],
      filteredProducts: []
    };
  },
  methods: {
    groupProducts() {
      this.filteredProducts.push({
        type: "Category",
        products: this.productsByCategory
      });
      this.filteredProducts.push({
        type: "Tag",
        products: this.productsByTag
      });
    }
  }
}

【讨论】:

  • 为什么要推两次?
  • 你也可以push一次,用逗号分隔参数
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-16
  • 2017-05-29
  • 2022-08-09
相关资源
最近更新 更多