英文:
How to get unique array of objects filtering by object key Vuex?
问题
以下是已翻译的内容:
"我期望获得一个新的对象数组,其中的 key 值 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) // 返回一个对象数组
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) // 返回重复项的数组
return flightsClasses
},
}
英文:
I'm expecting to obtain a new array of ojects with a none repeatable key value trip_class. But I'm getting still 30 object items instead of a single one or two. Using computed initial array of objects Vuex.
From this :
[
{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'}
]
I'd like to obtain this :
[
{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
},
答案1
得分: 0
这能解决吗?
acc.find((flightClass) => obj.trip_class === flightClass.trip_class );
英文:
Does this fix it?
acc.find((flightClass) => obj.trip_class === flightClass.trip_class );
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论