Skip to content

Instantly share code, notes, and snippets.

@im-ian
Last active April 23, 2025 08:28
Show Gist options
  • Select an option

  • Save im-ian/baff8ea1c20e1bc190f39501eb605e3f to your computer and use it in GitHub Desktop.

Select an option

Save im-ian/baff8ea1c20e1bc190f39501eb605e3f to your computer and use it in GitHub Desktop.
주어진 객체에서 특정 키를 찾아 경로를 반환하는 함수
/**
* 주어진 값이 object 타입인지 검사하는 함수
* @param {*} obj - 검사할 object
* @returns {boolean} - 검사할 값이 object라면 true, 아니라면 false를 반환
*/
function isObject(obj) {
return obj !== null && typeof obj === 'object';
}
/**
* 주어진 객체에서 특정 키를 찾아 경로를 반환하는 재귀함수
* @param {Object} obj - 검사할 object
* @param {string} key - object 내에서 찾아낼 key
* @returns {string[]} - 객체 내 키의 경로를 나타내는 문자열 배열
*/
function findPath(obj, key) {
const result = [];
const find = (obj, key, path) => {
if (isObject(obj)) {
for (const k in obj) {
if (k === key) {
result.push(path.concat(k).join('.'));
}
if (isObject(obj[k])) {
find(obj[k], key, path.concat(k));
}
}
}
};
find(obj, key, []);
return result;
}
@im-ian
Copy link
Author

im-ian commented Feb 5, 2024

const test = {
  a: { // a is here
    b: {
      c: 12,
      j: false,
    },
    f: {
      a: 13, // a is here
    },
    k: null,
  },
};

findPath(test, 'a'); // ['a', 'a.f.a']

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment