{
"key1": "str1",
"key2": {
"key3": "str3",
},
"key4": {
"key5": {
"key6": "str6",
"key7": "str7",
},
"key8": "str8",
},
"key9": "str9",
};
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") {
const val = this.recursion(obj[key], target);
if (val) {
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 />;