如何创建现有json的树

时间:2017-11-30 10:29:51

标签: javascript jquery json recursion tree

我想解析一个从api

获取的json

我有以下架构

tensor2[i,:]

我正在尝试关注但不能正常工作

nodes = [
    {
        id: 1,
        name: 'root1',
        key: 'value1'
        key1: 'value2'
        children: [
            { id: 2, name: 'child1' },
            { id: 3, name: 'child2' }
        ]
    },
    {
        id: 4,
        name: 'root2',
        key3: 'value3'
        key4: 'value4'
        children: [
            { id: 5, name: 'child2.1' },
            {
                id: 6,
                name: 'child2.2',
                key5: 'value5'
                key6: 'value6'
                children: [{
                    id: 7,
                    name: 'subsub',
                    children: [{
                        id: 8,
                        name: 'subsubsub'
                    }]
                }]
            }
        ]
    }
];

现在我想使用递归函数

以下面的格式转换上面的json
data = []

var nodesFun = function(n, data, cObj) {
    let obj = {}
    obj["name"] = n['name']
    if (n['children']) {
        console.log(obj);
        console.log("name--> "+n['name']);
        let childList = []
        for (let i=0; i < n['children'].length; i++){
            console.log("cname--> "+n['children'][i]['name']);
            childList.push({"name": n['children'][i]['name']})
            let dataObj = nodesFun(n['children'][i], data, obj)
            if (dataObj){
                data.push(dataObj)
            }
        }
        obj["children"] =  childList
        cObj["children"] =  obj
        return cObj
    }else{
      cObj["children"] =  obj
      return cObj
    }
}
nodesFun(nodes, data, {})
console.log(nodes);

2 个答案:

答案 0 :(得分:1)

您可以使用nodes和递归方法修改原始array#forEach数组。如果密钥包含key个字词,则会对节点的每个密钥进行迭代,并将其删除,如果它包含children再次调用deleteKey函数。

var nodes = [ { id: 1, name: 'root1', key: 'value1', key1: 'value2', children: [ { id: 2, name: 'child1' }, { id: 3, name: 'child2' } ] }, { id: 4, name: 'root2', key3: 'value3', key4: 'value4', children: [ { id: 5, name: 'child2.1' }, { id: 6, name: 'child2.2',key5: 'value5', key6: 'value6', children: [{ id: 7, name: 'subsub', children: [{ id: 8, name: 'subsubsub' }] }] } ] } ];

var deleteKey = (nodes) => {
  nodes.forEach(node => {
    Object.keys(node).forEach(k => {
      if(k.includes('key'))
        delete node[k];
      if(k == 'children')
        deleteKey(node[k]);
    })
  });
}
deleteKey(nodes);
console.log(nodes);
.as-console-wrapper { max-height: 100% !important; top: 0; }

如果您想要新的数组,可以使用array#reducearray#map

var nodes = [ { id: 1, name: 'root1', key: 'value1', key1: 'value2', children: [ { id: 2, name: 'child1' }, { id: 3, name: 'child2' } ] }, { id: 4, name: 'root2', key3: 'value3', key4: 'value4', children: [ { id: 5, name: 'child2.1' }, { id: 6, name: 'child2.2',key5: 'value5', key6: 'value6', children: [{ id: 7, name: 'subsub', children: [{ id: 8, name: 'subsubsub' }] }] } ] } ];

var removeKey = (nodes) => {
  return nodes.map(node => {
    return Object.keys(node).reduce((r, k) => {
      if(!k.includes('key'))
        r[k] = node[k];
      if(k == 'children')
        r[k] = removeKey(node[k]);        
      return r;
    },{});
  });
}
console.log(removeKey(nodes));
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:0)

该函数删除对象中不是id,name和children的所有键

let nodes = [
    {
        id: 1,
        name: 'root1',
        key: 'value1',
        key1: 'value2',
        children: [
            { id: 2, name: 'child1' },
            { id: 3, name: 'child2' }
        ]
    },
    {
        id: 4,
        name: 'root2',
        key3: 'value3',
        key4: 'value4',
        children: [
            { id: 5, name: 'child2.1' },
            {
                id: 6,
                name: 'child2.2',
                key5: 'value5',
                key6: 'value6',
                children: [{
                    id: 7,
                    name: 'subsub',
                    children: [{
                        id: 8,
                        name: 'subsubsub'
                    }]
                }]
            }
        ]
    }
];

const getFinalNode = function(arr){
  arr.forEach(function(obj, idx){
    let tmpObj = {
      id: obj.id,
      name: obj.name,
    }
    if(obj.children && obj.children.length){
      tmpObj.children = getFinalNode(obj.children)
    }
    arr[idx] = tmpObj
  })
  return arr
}
getFinalNode(nodes);
console.log(nodes)