查找对象中路径

{
  "key1": "str1",
  "key2": {
    "key3": "str3",
  },
  "key4": {
    "key5": {
      "key6": "str6",
      "key7": "str7",
    },
    "key8": "str8",
  },
  "key9": "str9",
};

传入查找的目标,并返回对象的路径

/**
 * defaultShowCode: true
 */
import React from "react";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      inputVal: "",
      value: "~",
      obj: {
        key1: "str1",
        key2: {
          key3: "str3",
        },
        key4: {
          key5: {
            key6: "str6",
            key7: "str7",
          },
          key8: "str8",
        },
        key9: "str9",
      },
    };
  }

  async onSeatch(obj, target) {
    if (!obj || !target) return;
    const data = await this.recursion(obj, target);
    this.setState({
      value: data,
    });
  }

  /**
   * 递归核心
   **/
  recursion(obj, target) {
    for (let key in obj) {
      if (obj[key] === target) {
        // 递归出口
        return [key];
      } else if (typeof obj[key] === "object") {
        // 如果在当前的key中找到了则有返回值,如果没有找到将返回 undefinde
        const val = this.recursion(obj[key], target);
        if (val) {
          // 如果有返回要将当前key 和返回的key 做链接
          return [key, val].flat();
        }
      }
    }
  }

  render() {
    return (
      <>
        <input
          type="text"
          onChange={(e) => this.setState({ inputVal: e.target.value })}
        />
        <button
          onClick={this.onSeatch.bind(
            this,
            this.state.obj,
            this.state.inputVal
          )}
        >
          查找
        </button>
        <p>
          查询结果:
          {this.state.value ? JSON.stringify(this.state.value) : "没有找到~"}
        </p>
      </>
    );
  }
}

export default () => <App />;
上次更新:
贡献者: 郑壮