javascript 如何通过对象键Vuex获得唯一的对象数组?

6l7fqoea  于 2023-05-16  发布在  Java
关注(0)|答案(1)|浏览(211)

我希望获得一个新的对象数组,其键值为不可重复的trip_class。但是我仍然得到了30个对象项,而不是一个或两个。使用计算对象的初始数组Vuex。
从这里:

[
    {name: 'john', trip_class: 0, lastname: 'lastname'}, 
    {name: 'Don', trip_class: 1, lastname: 'lastname'},
    {name: 'Joshua', trip_class: 1, lastname: 'lastname'},
    {name: 'Mary', trip_class: 2, lastname: 'lastname'}
]

我想得到这个

[
    {name: 'john', trip_class: 0, lastname: 'lastname'}, 
    {name: 'Don', trip_class: 1, lastname: 'lastname'},
    {name: 'Mary', trip_class: 2, lastname: 'lastname'}
]
computed: {
            flights() {
              return this.$store.getters.getFlights;
            },
            flightsClasses() {
              console.log(this.flights)    // returns an array of objects
              let flightsClasses = this.flights 
                flightsClasses.reduce((acc, obj)=>{
                  var exist = acc.find((flightClass) => obj.trip_class === flightClass );
                  if(!exist){
                    acc.push(obj);
                  }
                  return acc;
                },[]);

              console.log('flightsClasses',flightsClasses)    // returns repeatable items array
              return flightsClasses
            },
swvgeqrz

swvgeqrz1#

这能解决问题吗
acc.find((flightClass) => obj.trip_class === flightClass.trip_class );

相关问题