如何在NuxtJS中通过Lodash按rg_ext全键值匹配分组数组
问题:按对象内所有键值完全匹配分组数组
给定如下RoomsPrices数组:
const RoomsPrices = ref([ { rg_ext: { class: 5, quality: 0, sex: 0, bathroom: 2, bedding: 3, family: 0, capacity: 2, club: 0, }, room_name: "2 Bedrooms Double Suite (full double bed)", cost: 10000, priceid: 15464, }, { rg_ext: { class: 3, quality: 0, sex: 0, bathroom: 2, bedding: 2, family: 0, capacity: 3, club: 0, }, room_name: "3 Bedrooms Double Suite (full double bed)", cost: 14000, priceid: 12464, }, { rg_ext: { class: 3, quality: 0, sex: 0, bathroom: 2, bedding: 2, family: 0, capacity: 3, club: 0, }, room_name: "3 Bedrooms Double Suite (full double bed)", cost: 14000, priceid: 12464, }, { rg_ext: { class: 5, quality: 0, sex: 0, bathroom: 2, bedding: 3, family: 0, capacity: 2, club: 0, }, room_name: "2 Bedrooms Double Suite (full double bed)", cost: 16300, priceid: 36464, }, ]);
希望按照rg_ext对象内所有键值完全匹配的规则分组,但使用Lodash的useGroupBy时:
const RoomGroup = computed(() => { const GP = useGroupBy(RoomsPrices.value, "rg_ext"); return GP; });
返回的是4个独立对象,而非预期的2组,需解决分组问题。
原因分析
Lodash的groupBy直接传入对象属性名时,会将对象引用作为分组键。即使两个rg_ext对象的内容完全一致,它们也是不同的引用,因此会被分到不同组。
解决方案
方法1:结合Lodash生成自定义分组键
将rg_ext对象序列化为字符串(比如JSON字符串)作为分组键,内容相同的对象会生成相同的字符串,从而被归为一组:
import { useGroupBy } from '@vueuse/integrations/useLodash' const RoomGroup = computed(() => { const GP = useGroupBy(RoomsPrices.value, item => JSON.stringify(item.rg_ext)); return GP; });
方法2:手动实现分组逻辑
如果不想依赖Lodash,可以自己遍历数组,通过固定顺序拼接键值对生成唯一标识,确保相同内容的对象分到同一组:
const RoomGroup = computed(() => { const groups = {}; RoomsPrices.value.forEach(item => { // 先对rg_ext的键排序,避免因键顺序不同导致标识不一致 const sortedKeys = Object.keys(item.rg_ext).sort(); // 拼接成唯一字符串键 const groupKey = sortedKeys.map(key => `${key}:${item.rg_ext[key]}`).join('|'); if (!groups[groupKey]) { groups[groupKey] = []; } groups[groupKey].push(item); }); return groups; });
注意:若存在对象键顺序不确定的场景,推荐使用方法2,避免
JSON.stringify因键顺序差异生成不同字符串的问题。
内容的提问来源于stack exchange,提问作者Vinay Thakur
相关产品推荐
相关产品推荐

