js 递归查询的问题

小花生
  • 78

我想在nodes这个数组可能有N层,我想在最后一层children的数组对象里面,每个对象加一些属性,如下

nodes = [

{
  title: 'parent 1',
  key: '100',
  children: [
    {
      title: 'parent 1-0',
      key: '1001',
      children: [
        { title: 'leaf', key: '10010' },
        { title: 'leaf', key: '10011' },
        { title: 'leaf', key: '10012' }
      ]
    },
  ]
}

];

目的:
nodes = [

{
  title: 'parent 1',
  key: '100',
  children: [
    {
      title: 'parent 1-0',
      key: '1001',
      children: [
        { title: 'leaf', key: '10010',test:'aaaa '},
        { title: 'leaf', key: '10011',test:'aaaa ' },
        { title: 'leaf', key: '10012',test:'aaaa '}
      ]
    },
  ]
}

];

回复
阅读 743
3 个回答

这样行吗?

function getChildren(nodes){
    if(nodes.children&&nodes.children.length){
        getChildren(nodes.children)
    }else{
        nodes.forEach((i,n)=>n.test="aaaa")
    }
}

这不就正常递归吗,判断children和children的长度是否为真,真就接着递归,假就加你要的属性

function forEach(arr) {
    if (Array.isArray(arr)) {
        for (var i = 0; i < arr.length; ++i) {
            var obj = arr[i];
            if ("children" in obj) forEach(obj.children);
            else obj.test = "aaaa";
        }
    }
    return arr;
}
console.log(forEach(nodes));
你知道吗?

宣传栏