获取js中嵌套对象的所有键

发布于 2025-01-17 00:07:41 字数 1197 浏览 1 评论 0原文

我有一个非常简单的问题,假设下面的对象

const x={a:{b:"b"},c:{b:"b"}}

1)我想要一个方法来返回嵌套对象中的所有键,例如[“a”,“b”,“c”] 2)我想要一个方法来返回我的特定键的所有路径,例如 b=>["a","c"] 使用lodash,我们有方法_.get(obj,path),它通过我们传递给get方法的路径返回对象值,但有时我们没有路径或路径模糊怎么办 下面的代码以某种方式解决问题

const findPath = (ob, key) => {
  const path = [];
  const keyExists = (obj) => {
    if (!obj || (typeof obj !== "object" && !Array.isArray(obj))) {
      return false;
    }
    else if (obj.hasOwnProperty(key)) {
      return true;
    }
    else if (Array.isArray(obj)) {
      let parentKey = path.length ? path.pop() : "";

      for (let i = 0; i < obj.length; i++) {
        path.push(`${parentKey}[${i}]`);
        const result = keyExists(obj[i], key);
        if (result) {
          return result;
        }
        path.pop();
      }
    }
    else {
      for (const k in obj) {
        path.push(k);
        const result = keyExists(obj[k], key);
        if (result) {
          return result;
        }
        path.pop();
      }
    }
    return false;
  };

  keyExists(ob);

  return path.join(".");
}

上面的代码的问题是:1)不干净 2)不返回所有路径,例如 x={a:{b:"b"},c:{b:"b"}}仅返回“a”

i have very simple question assume bellow object

const x={a:{b:"b"},c:{b:"b"}}

1)I want a method to return all of keys in my nested object eg ["a","b","c"]
2)I want a method to return all paths of my specific key eg for b=>["a","c"]
using lodash we have method _.get(obj,path) that return object value by the path we pass to get method but what about times we haven't path or path is vague
bellow code solve problem somehow

const findPath = (ob, key) => {
  const path = [];
  const keyExists = (obj) => {
    if (!obj || (typeof obj !== "object" && !Array.isArray(obj))) {
      return false;
    }
    else if (obj.hasOwnProperty(key)) {
      return true;
    }
    else if (Array.isArray(obj)) {
      let parentKey = path.length ? path.pop() : "";

      for (let i = 0; i < obj.length; i++) {
        path.push(`${parentKey}[${i}]`);
        const result = keyExists(obj[i], key);
        if (result) {
          return result;
        }
        path.pop();
      }
    }
    else {
      for (const k in obj) {
        path.push(k);
        const result = keyExists(obj[k], key);
        if (result) {
          return result;
        }
        path.pop();
      }
    }
    return false;
  };

  keyExists(ob);

  return path.join(".");
}

problems with above code are:1)is not clean 2)don't return all paths for example in x={a:{b:"b"},c:{b:"b"}} return just "a"

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

阳光的暖冬 2025-01-24 00:07:42

您可以采用递归方法并检查键是否存在,然后返回此键,包装在嵌套数组中或返回嵌套对象的结果并将其与实际键映射或返回一个空数组,这不是平面的条目地图。

const
    findPathes = (object, key) => key in object 
        ? [[key]]
        : Object.entries(object).flatMap(([k, v]) => {
            if (!v || typeof v !== 'object') return [];
            const pathes = findPathes(v, key);
            return pathes.length
                ? pathes.map(a => [k, ...a])
                : [];
        }),
    data = { a: { b: "b" }, c: { b: "b" }, d: { e: { f: { g: "g" }, h: { b: 'b' } } } } ;
    

console.log(findPathes(data, 'b'));
.as-console-wrapper { max-height: 100% !important; top: 0; }

You could take a recursive approach and check if the key exists, then return this key, wrapped in a nested array or return the result of nested objects and map this with the actual key or return an empty array, which is no entry for a flat map.

const
    findPathes = (object, key) => key in object 
        ? [[key]]
        : Object.entries(object).flatMap(([k, v]) => {
            if (!v || typeof v !== 'object') return [];
            const pathes = findPathes(v, key);
            return pathes.length
                ? pathes.map(a => [k, ...a])
                : [];
        }),
    data = { a: { b: "b" }, c: { b: "b" }, d: { e: { f: { g: "g" }, h: { b: 'b' } } } } ;
    

console.log(findPathes(data, 'b'));
.as-console-wrapper { max-height: 100% !important; top: 0; }

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文