From 9861bcbf18e19448a3405c00f6e616ea06dec0ca Mon Sep 17 00:00:00 2001 From: Duncan McClean Date: Fri, 16 Aug 2024 17:36:30 +0100 Subject: [PATCH 1/2] When the `key` exists, use that --- resources/js/components/fieldtypes/HasInputOptions.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/resources/js/components/fieldtypes/HasInputOptions.js b/resources/js/components/fieldtypes/HasInputOptions.js index e2e6e3b176c..5a64d724cb0 100644 --- a/resources/js/components/fieldtypes/HasInputOptions.js +++ b/resources/js/components/fieldtypes/HasInputOptions.js @@ -13,7 +13,7 @@ export default { return _.map(options, (option) => { if (typeof option === 'object') { return { - 'value': option.value, + 'value': option.key || option.value, 'label': __(option.label) || option.value }; } From 6f6ab69f640b3405723a0cd08129b82a12331e80 Mon Sep 17 00:00:00 2001 From: Jason Varga Date: Fri, 16 Aug 2024 14:12:46 -0400 Subject: [PATCH 2/2] add test and adjust implementation --- .../js/components/fieldtypes/HasInputOptions.js | 13 +++++++++++-- resources/js/tests/NormalizeInputOptions.test.js | 12 +++++++++++- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/resources/js/components/fieldtypes/HasInputOptions.js b/resources/js/components/fieldtypes/HasInputOptions.js index 5a64d724cb0..e829d936446 100644 --- a/resources/js/components/fieldtypes/HasInputOptions.js +++ b/resources/js/components/fieldtypes/HasInputOptions.js @@ -12,9 +12,18 @@ export default { return _.map(options, (option) => { if (typeof option === 'object') { + let valueKey = 'value'; + let labelKey = 'label'; + + // Support both {key: '', value: ''} and {value: '', label: ''} formats. + if (option.hasOwnProperty('key')) { + valueKey = 'key'; + labelKey = 'value'; + } + return { - 'value': option.key || option.value, - 'label': __(option.label) || option.value + 'value': option[valueKey], + 'label': __(option[labelKey]) || option[valueKey] }; } diff --git a/resources/js/tests/NormalizeInputOptions.test.js b/resources/js/tests/NormalizeInputOptions.test.js index 525c35c99c8..4a96af59935 100644 --- a/resources/js/tests/NormalizeInputOptions.test.js +++ b/resources/js/tests/NormalizeInputOptions.test.js @@ -46,7 +46,7 @@ it('normalizes input options with object', () => { ]); }); -it('normalizes input options with array of objects', () => { +it('normalizes input options with array of objects with value label keys', () => { expect(normalizeInputOptions([ {value: 'one', label: 'One'}, {value: 'two', label: 'Two'} @@ -55,3 +55,13 @@ it('normalizes input options with array of objects', () => { {value: 'two', label: 'Two'} ]); }); + +it('normalizes input options with array of objects with key value keys', () => { + expect(normalizeInputOptions([ + {key: 'one', value: 'One'}, + {key: 'two', value: 'Two'} + ])).toEqual([ + {value: 'one', label: 'Uno'}, + {value: 'two', label: 'Two'} + ]); +});