Skip to content

Commit

Permalink
Merge pull request #101 from prgrms-fe-devcourse/100-feature/replacet…
Browse files Browse the repository at this point in the history
…extproperties

Feat: replaceTextProperties
  • Loading branch information
shlee9999 authored Sep 30, 2024
2 parents 2e40d7e + f34dd37 commit 2d1aeae
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/hooks/useFetch.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import replaceTextProperties from '@/utils/extractInnermostValues';
import { useEffect, useState } from 'react';
import { xml2json } from 'xml-js';

Expand All @@ -17,7 +18,7 @@ export default function useFetch<T>(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<T>(jsonData));
} catch (error) {
console.error('Error fetching data:', error);
} finally {
Expand Down
35 changes: 35 additions & 0 deletions src/utils/extractInnermostValues.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/**
* 객체의 '_text' 속성을 해당 값으로 대체하는 함수
*
* @template T - 입력 객체의 타입
* @param {T} obj - 가장 안쪽의 값을 추출할 객체
* @returns {T} '_text' 속성이 해당 값으로 대체된 입력 객체와 동일한 구조의 새로운 객체
*/
export default function replaceTextProperties<T>(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;
}

0 comments on commit 2d1aeae

Please sign in to comment.