From f34dd371ab799753202cab361704ebd42bf3056b Mon Sep 17 00:00:00 2001 From: shlee9999 <95556588+shlee9999@users.noreply.github.com> Date: Mon, 30 Sep 2024 12:36:15 +0900 Subject: [PATCH] Feat: replaceTextProperties --- src/hooks/useFetch.ts | 3 ++- src/utils/extractInnermostValues.ts | 35 +++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 src/utils/extractInnermostValues.ts diff --git a/src/hooks/useFetch.ts b/src/hooks/useFetch.ts index e16e756..82a6d3c 100644 --- a/src/hooks/useFetch.ts +++ b/src/hooks/useFetch.ts @@ -1,3 +1,4 @@ +import replaceTextProperties from '@/utils/extractInnermostValues'; import { useEffect, useState } from 'react'; import { xml2json } from 'xml-js'; @@ -17,7 +18,7 @@ export default function useFetch(url: string) { const response = await fetch(url); const xmlText = await response.text(); const jsonData = JSON.parse(xml2json(xmlText, { compact: true, spaces: 2 })); - setData(jsonData); + setData(replaceTextProperties(jsonData)); } catch (error) { console.error('Error fetching data:', error); } finally { diff --git a/src/utils/extractInnermostValues.ts b/src/utils/extractInnermostValues.ts new file mode 100644 index 0000000..962ba8a --- /dev/null +++ b/src/utils/extractInnermostValues.ts @@ -0,0 +1,35 @@ +/** + * 객체의 '_text' 속성을 해당 값으로 대체하는 함수 + * + * @template T - 입력 객체의 타입 + * @param {T} obj - 가장 안쪽의 값을 추출할 객체 + * @returns {T} '_text' 속성이 해당 값으로 대체된 입력 객체와 동일한 구조의 새로운 객체 + */ +export default function replaceTextProperties(obj: T): T { + if (typeof obj !== 'object' || obj === null) { + return obj; + } + + if (Array.isArray(obj)) { + return obj.map(replaceTextProperties) as unknown as T; + } + + if (obj && typeof obj === 'object' && '_text' in obj) { + const textValue = obj._text; + if (typeof textValue === 'string') { + const parsedValue = +textValue; + if (!isNaN(parsedValue)) { + return parsedValue as T; + } + } + return textValue as T; + } + + const result: { [key: string]: T[keyof T] } = {}; + + for (const [key, value] of Object.entries(obj)) { + result[key] = replaceTextProperties(value); + } + + return result as T; +}