从json获取所有子节点 [英] get all child nodes from json

查看:158
本文介绍了从json获取所有子节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下json:

    var source=[{'k':'01'},
                {'k':'02', 'children': [
                    {'k':'05'},
                    {'k':'06', 'children': [
                        {'k':'ABC'},
                        {'k':'PQR'}
                    ]},
                    {'k':'07'}
                ]},
                {'k':'03'}];

我希望能够为k指定一个值,并取回所有的孩子(以及孙子和曾孙等).

I want to be able to specify a value for k and get back all of the children (and grandchildren and great-grandchildren, etc.).

例如,如果我提供'02',我想接收

For instance if I provide '02', I want to receive

            [
              {'k':'05'},
              {'k':'06'},
              {'k':'ABC'},
              {'k':'PQR'},  
              {'k':'07'}
            ]

推荐答案

尝试以下操作:

function mergeChildren(sources) {
  var children = [];
  for (var index in sources) {
    var source = sources[index];
    children.push({k: source.k});
    if (source.children) {
      children = children.concat(mergeChildren(source.children))
    }
  }
  return children;
}

function findChildrenForK(sources, k) {
  for (var index in sources) {
    var source = sources[index];
    if (source.k === k) {
       if (source.children) {
         return mergeChildren(source.children);
       }
    }
  }
}

findChildrenForK扫描对象数组sources,并将其属性k与提供给该函数的k进行匹配.如果找到匹配的对象,则在该对象的children属性上调用mergeChildren.

findChildrenForK scans through an array of objects, sources, and matches their property k to the k supplied to the function. If a matching object is found, we call mergeChildren on that object's children property.

mergeChildren遍历分配给它的对象数组,并将每个键推入称为children的数组.如果任何对象本身都有子对象,则通过递归调用mergeChildren并使用

mergeChildren iterates through the array of objects given to it, and pushes each key into an array, called children. If any objects themselves have children, we concatenate them to our children accumulator by calling mergeChildren recursively and using the Array#concat function.

在此 JSFiddle 中查看包含您的示例数据的实际脚本.

See the script in action with your sample data in this JSFiddle.

这篇关于从json获取所有子节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆