javascript - 尝试在树javascript中递归查找元素
问题描述
我试图弄清楚如何在 json 树中递归搜索元素。例如,我现在正在尝试达到“水果”,但不知道该怎么做。这是我的 json 对象
[
{
"_id": "604cab0acbdb8c1060698419",
"name": "Grocery",
"children": [
{
"children": [
{
"name": "Fruits",
"price": "200"
}
],
"_id": "604cad9b4ae51310c6f313f6",
"name": "Potatoes",
"price": "200"
},
{
"children": [],
"_id": "604cae721257d510e679a467",
"name": "Vegetables"
}
],
"date": "2021-03-13T12:07:38.186Z",
"__v": 0
} ]
function findName(name, tree) {
if(tree.children.name == name {
return tree;
}
if(tree.child == 0) {
return
}
return findName(name, tree);
};
解决方案
const object = [
{
"_id": "604cab0acbdb8c1060698419",
"name": "Grocery",
"children": [
{
"children": [
{
"name": "Fruits",
"price": "200"
}
],
"_id": "604cad9b4ae51310c6f313f6",
"name": "Potatoes",
"price": "200"
},
{
"children": [],
"_id": "604cae721257d510e679a467",
"name": "Vegetables"
}
],
"date": "2021-03-13T12:07:38.186Z",
"__v": 0
} ]
function find(name, tree) {
// tree is undefined, return `undefined` (base case)
if (!tree) return
if (Array.isArray(tree)) {
// tree is an array
// so iterate over every object in the array
for (let i = 0; i < tree.length; i++) {
const obj = tree[i]
const result = find(name, obj)
// `find` returned non-undefined value
// means match is found, return it
if (result) return result
// no match found in `obj` so continue
}
} else if (tree.name === name) {
// `tree` is a key-value object
// and has matching `name`
return tree
}
// if no tree matching `name` found on the current `tree`
// try finding on its `children`
return find(name, tree.children)
}
console.log(find("Fruits", object))
推荐阅读
- python - 共识/集群一组 Python 中的可变长度列表?
- c++ - 使用 cmake 对特定文件进行预验证或后验证
- azure - Azure 逻辑应用,解析 JSON,但可能为空
- ios - 在 tableview 单元格中正确包装文本
- javascript - 首次加载应用程序时,如何在我的所有 .js 文件中设置一些变量?在用户看到之前,我需要这些来按比例分配我的所有屏幕尺寸
- bash - Bash shell 脚本不执行命令 docker entrypoint
- c++ - 为什么 openvr GetPoseActionDataForNextFrame 没有获得控制器的位置
- excel - 使用 VBA 为列表中的特定单词着色
- php - 通过 url 发送多个项目时清除 Woocommerce 购物车
- c++ - 向量 - 首先出现 k 次的值