From 8fb373fc2a75a81afe89e37abfac2926cc352c64 Mon Sep 17 00:00:00 2001 From: Adam Berecz Date: Mon, 16 Sep 2024 16:54:14 +0200 Subject: [PATCH] fix: option should display as selected even when value is an object --- src/composables/useOptions.js | 6 +++++- src/utils/objectsEqual.js | 37 +++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) create mode 100644 src/utils/objectsEqual.js diff --git a/src/composables/useOptions.js b/src/composables/useOptions.js index 7d16475..87ae129 100644 --- a/src/composables/useOptions.js +++ b/src/composables/useOptions.js @@ -3,6 +3,7 @@ import normalize from './../utils/normalize' import isObject from './../utils/isObject' import isNullish from './../utils/isNullish' import arraysEqual from './../utils/arraysEqual' +import objectsEqual from './../utils/objectsEqual' import toRef from './../utils/toRef' export default function useOptions (props, context, dep) @@ -325,7 +326,10 @@ export default function useOptions (props, context, dep) switch (mode.value) { case 'single': - return !isNullish(iv.value) && iv.value[valueProp.value] == option[valueProp.value] + return !isNullish(iv.value) && ( + iv.value[valueProp.value] == option[valueProp.value] || + (typeof iv.value[valueProp.value] === 'object' && typeof option[valueProp.value] === 'object' && objectsEqual(iv.value[valueProp.value], option[valueProp.value])) + ) case 'tags': case 'multiple': diff --git a/src/utils/objectsEqual.js b/src/utils/objectsEqual.js new file mode 100644 index 0000000..23ad800 --- /dev/null +++ b/src/utils/objectsEqual.js @@ -0,0 +1,37 @@ +const objectsEqual = (obj1, obj2) => { + // If both are strictly equal, return true + if (obj1 === obj2) { + return true + } + + // If either is not an object or is null, return false (handles primitive types and null) + if (typeof obj1 !== 'object' || obj1 === null || typeof obj2 !== 'object' || obj2 === null) { + return false + } + + // Get the keys of both objects + const keys1 = Object.keys(obj1) + const keys2 = Object.keys(obj2) + + // If they have a different number of keys, they're not equal + if (keys1.length !== keys2.length) { + return false + } + + // Compare each key-value pair recursively + for (let key of keys1) { + // Check if both objects have the same key + if (!keys2.includes(key)) { + return false + } + + // Recursively compare the values + if (!objectsEqual(obj1[key], obj2[key])) { + return false + } + } + + return true +} + +export default objectsEqual \ No newline at end of file