인생마커

개요

자바스크립트에서 깊이 중첩되어 있는 객체나 배열에서 특정 값을 찾는 것은 꽤 피곤하고 번거로운 작업입니다.

 

객체를 일일히 탐색할 수도 있고 중첩된 구조를 탐색하기 위해 복잡한 재귀 함수를 작성해야 할 수도 있습니다.

 

여기서 저는 JSON.stringfy를 활용하여 사용할 수 있는 간단한 Util 함수를 작성해보았습니다.

 

deepfind

 

Javascript

/**
 * @param entireObj 대상 객체 또는 배열
 * @param key 찾으려는 value의 key
 * @param value 찾으려는 value
 * @param type 
 *
 * "all": 중첩된 구조 내에서 원하는 값의 모든 발생을 배열로 반환합니다.
 * 
 * "first": 중첩된 구조 내에서 원하는 값의 마지막 발생을 찾습니다.
 * 
 * "last": 중첩된 구조 내에서 원하는 값의 첫 번째 발생을 찾습니다.
 * 
 * @return 해당 객체
*/
function deepFind(entireObj, key, value, type) {
    let foundObj;
    JSON.stringify(entireObj, (_, nestedValue) => {
        switch(type) {
            case "first": {
                if (!foundObj && nestedValue && nestedValue[key] === value) {
                    foundObj = nestedValue;
                  }
                return nestedValue;
            }
            case "last": {
                if (nestedValue && nestedValue[key] === value) {
                    foundObj = nestedValue;
                  }
                  return nestedValue;
            }
            case "all": { 
                if (nestedValue && nestedValue[key] === value) {
                    foundObj = foundObj ? foundObj.concat([nestedValue]) : [nestedValue];
                  }
                  return nestedValue;
            }
        }
      
    });
    return foundObj;
  };

Typescript

enum FIND_TYPE {
    FIRST = "first",
    LAST = "last",
    ALL = "all"
}
function deepFind<O,V>(entireObj: O, key: string, value: V, type: FIND_TYPE) {
    let foundObj: any;
    JSON.stringify(entireObj, (_, nestedValue) => {
        switch(type) {
            case FIND_TYPE.FIRST: {
                if (!foundObj && nestedValue && nestedValue[key] === value) {
                    foundObj = nestedValue;
                  }
                return nestedValue;
            }
            case FIND_TYPE.LAST: {
                if (nestedValue && nestedValue[key] === value) {
                    foundObj = nestedValue;
                  }
                  return nestedValue;
            }
            case FIND_TYPE.ALL: { 
                if (nestedValue && nestedValue[key] === value) {
                    foundObj = foundObj ? foundObj.concat([nestedValue]) : [nestedValue];
                  }
                  return nestedValue;
            }
        }
      
    });
    return foundObj;
  };

 

위 함수를 사용하면 복잡한 재귀 호출 로직 없이도 중첩된 객체의 값들을 간편하게 탐색할 수 있습니다. 

 

JSON.stringfy는 중첩된 형태의 객체 또는 배열을 직렬화 하기 때문에 자연스런 재귀적 특성을 가지고 있고 문자열화 프로세스 동안 각 중첩된 객체에서 실행되는 대체함수를 전달합니다.

 

때문에 깊은 탐색을 요하는 상황에서 따로 재귀 호출 로직을 작성하지 않고 간단히 활용할 수 있습니다.

 

반환되는 객체는 entireObj안의 객체와 완전히 동일한 객체임을 주의합시다.

 

'Utils' 카테고리의 다른 글

GoJS 메모리 누수(Memory leak)와 성능 개선  (0) 2023.07.24
Cron 해석 라이브러리  (0) 2023.06.27
JSON Server  (0) 2022.02.17
profile

인생마커

@Cottonwood__

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!