如何在VueJS中使用for循环对属性中的数据进行分组

Bar*_*vet 5 vue.js

我正在尝试解决如何使用 VueJS 中的 for 循环在两个级别对数据进行分组

例如,我有一个 VueJS 应用程序,其中包含以下数据:

cars: [{
  "make": "Ford",
  "model": "Mustang"
}, {
  "make": "Ford",
  "model": "Thunderbird"
}, {
  "make": "Ford",
  "model": "Fairlane"
}, {
  "make": "Chevrolet",
  "model": "Camaro"
}, {
  "make": "Chevrolet",
  "model": "Chevelle"
}, {
  "make": "Plymouth",
  "model": "Barracuda"
}]
Run Code Online (Sandbox Code Playgroud)

使用 for 循环遍历汽车很简单:

<div v-for="car in cars">
  <div>Make: {{ car.make }}</div>
  <div>Model: {{ car.model }}</div>  
</div>
Run Code Online (Sandbox Code Playgroud)

但是如果我想按品牌对模型进行分组怎么办?我追求的输出是:

Ford
  Mustang
  Thunderbird
  Fairlane
Chevrolet
  Camaro
  Chevelle
Plymouth
  Barracuda
Run Code Online (Sandbox Code Playgroud)

在 VueJS 中执行此操作的最佳方法是什么?

Ste*_*mas 8

@DigitalDrifter 有一个很好的解决方案,但您可能会发现以下内容更易于阅读。但是,它的效率较低,所以我绝对不会将它用于大型收藏(例如数千辆汽车)。

computed: {
    makes() {
        const makes = new Set();
        this.cars.forEach(car => makes.add(car.make);
        return Array.from(makes); 
    }
},
methods: {
    models(make) {
        return this.cars
            .filter(car => car.make === make)
            .map(car => car.model);
    }
}
Run Code Online (Sandbox Code Playgroud)

并在模板中

<div v-for="(make, index) in makes" :key="index">
    <p>Make: {{ make }}</p>
    <ul>
        <li v-for="(model, innerIndex) in models(make)" :key="innerIndex">
            {{ model }}
        </li>
    </ul>
</div>
Run Code Online (Sandbox Code Playgroud)


Dig*_*ter 5

reduce您可以在计算属性中使用:

computed: {
  groups () {
    return this.cars.reduce((carry, current) => {
      if (carry.hasOwnProperty(current.make) && Array.isArray(carry[current.make])) {
        carry[current.make].push(current.model)
      } else {
        Object.assign(carry, { [current.make]: [current.model] })
      }
      return carry
    }, {})
  }
}
Run Code Online (Sandbox Code Playgroud)

该模板可以循环组,例如:

<div v-for="(make, index) in Object.keys(groups)" :key="index">
  <p>Make: {{ make }}</p>
  <ul>
  <li v-for="(model, innerIndex) in groups[make]" :key="innerIndex">
    {{ model }}
  </li>
  </ul>
</div>
Run Code Online (Sandbox Code Playgroud)