【问题标题】:i want this output using recursive function [closed]我想要这个输出使用递归函数[关闭]
【发布时间】:2018-09-26 18:57:30
【问题描述】:

如何编写最好的 javascript 函数来获取此输出。 ['1','p1','p11','2','p2','p21'] 用于此输入。

const arr = [{

        "children": [{
            "property1": "1",

            "children": [{
                "property1": "p1",

                "children": [{
                    "property1": "p11",

                    "children": [

                    ]
                }]
            }]
        }]
    },
    {

        "children": [{
            "property1": "2",

            "children": [{
                "property1": "p2",

                "children": [{
                    "property1": "p21",

                    "children": [

                    ]
                }]
            }]
        }]
    }
]

如何使用递归函数获取输出。这是孩子们的循环。如果子项长度为 0,则不要添加,否则添加 property1 的数组。

【问题讨论】:

标签: javascript ecmascript-6


【解决方案1】:

您可以为此编写一个简单的递归函数。

  • 首先检查当前数组元素或子元素是否包含property1。如果存在,只需将property1 推送到结果数组。

  • 然后你需要检查孩子是否有自己的孩子(或子孩子),如果它有自己的孩子而不是递归调用getProperty()方法,将孩子数组作为新参数传递给函数结果数组。

const arr = [{ "children": [{ "property1": "1", "children": [{ "property1": "p1", "children": [{ "property1": "p11", "children": [ ] }] }] }] }, { "children": [{ "property1": "2", "children": [{ "property1": "p2", "children": [{ "property1": "p21", "children": [ ] }] }] }] } ];

function getProperty(arr, result){
  for(var i = 0; i < arr.length; i++){
    if(arr[i].property1)
      result.push(arr[i].property1);
    if(arr[i].children && arr[i].children.length)
      getProperty(arr[i].children, result);
  }
}
let result = [];
getProperty(arr,result)
console.log(result);

【讨论】:

  • 它有效,但这是正确的方法吗?
猜你喜欢
  • 2016-04-16
  • 2021-12-13
  • 2012-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-09
  • 2023-03-18
  • 1970-01-01
相关资源
最近更新 更多