地图返回返回递归的最后迭代?

时间:2018-11-19 13:42:42

标签: javascript

我正在使用递归逐步遍历此对象的子级数组。但是,它正在返回顶级父母。对象数组是:

>>> a = 5
>>> b = 6
>>> a^b
3

我的最终目标是将对象保存到一个新的数组中,仅将名称和orgId作为每个父母和孩子的对象。

    101 (5 decimal)
XOR 110 (6 decimal)
-------------------
    011 (3 decimal)

但是,当我通过使用递归的此函数传递它时,它仅返回'org.name':const orgs = { children:[{name:'Core Enginerinng Ops', orgId:741, children:[{name:'Child Engineering Ops', orgId:5656, children:[{name: 'Child Engineering Last LEVEL AHAHHH', orgid:6969}]},{name: 'Child 2 Engineering OPS', orgId: 852}]},{name: 'Data Services Engineering', orgId: 456, children:[{name:'Child Data Services', orgId:978},{name: 'Child 2 Data Services', orgId: 354}]}] } 。我对递归并不满意,但是flattenOrgs = (organizations) => { const flatArray =organizations.map(org => { if (org.children && org.children.length > 0) { this.flattenOrgs(org.children) } console.log(org.name) return org.name }) return flatArray } 不会按预期打印出每个单独的名称对我来说是没有意义的……但是它不会返回该名称?

编辑 ["Core Enginerinng Ops", "Data Services Engineering"]返回之前

  

Child Engineering Last LEVEL AHAHHH

     

儿童工程作业

     

Child 2 Engineering OPS

     

核心引擎运营

     

儿童数据服务

     

儿童2数据服务

     

数据服务工程

2 个答案:

答案 0 :(得分:1)

可以减少数组而不是映射,因为还需要子元素。

const
    orgs = { children: [{ name: 'Core Enginerinng Ops', orgId: 741, children: [{ name: 'Child Engineering Ops', orgId: 5656, children: [{ name: 'Child Engineering Last LEVEL AHAHHH', orgid: 6969 }] }, { name: 'Child 2 Engineering OPS', orgId: 852 }] }, { name: 'Data Services Engineering', orgId: 456, children: [{ name: 'Child Data Services', orgId: 978 }, { name: 'Child 2 Data Services', orgId: 354 }] }] },
    flattenOrgs = (organizations) =>
        organizations.reduce((r, { name, orgId, children }) => 
            r.concat({ name, orgId }, flattenOrgs(children || [])), []);

console.log(flattenOrgs(orgs.children));
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:0)

我希望下面的代码能满足您的期望:

namespace MyProject.Pages
{
public sealed partial class MainUserControl : UserControl
{

    public StackPanel cPanelQuestion;

    public MainUserControl()
    {
        this.InitializeComponent();
        cPanelQuestion = this.panelQuestion;

    }

    public object QuestionContent
    {
        get { return (object)GetValue(QuestionContentProperty); }
        set { SetValue(QuestionContentProperty, value); }
    }

    // Using a DependencyProperty as the backing store for Body.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty QuestionContentProperty =
        DependencyProperty.Register("QuestionContent", typeof(object), typeof(MainUserControl), null);



}