所选元素在哪些元素中?

时间:2019-10-15 18:44:43

标签: javascript angular typescript

我有一个数组。数组中的元素代表菜单元素。我想根据我选择的菜单项创建“面包屑”。但是,它在工作3个深度后会动态提供错误。

{
  "label": "New Post"
}

例如,如果我选择的元素是;

[
  {
    "label": "Posts"
  },
  {
    "label": "New Post"
  }
]

我想得到

{
  "label": "Edit Profile"
}



如果我选择的元素是;

[
  {
    "label": "Settings"
  },
  {
    "label": "User"
  },
  {
    "label": "Edit Profile"
  }
]


我想得到

"""
Usage:
  test.py [tls [--true|--false]]
"""
from docopt import docopt
arguments = docopt(__doc__)
if arguments['tls'] and not (arguments['--true'] or arguments['--false']):
    arguments['--true'] = True

我不知道如何找到所选元素的父级。我该怎么办?

1 个答案:

答案 0 :(得分:1)

我已经解决了问题。

menuArray = [{
    "label": "Dashboard"
  },
  {
    "label": "Products",
    "items": [{
        "label": "All Products"
      },
      {
        "label": "New Product"
      },
      {
        "label": "Product Categories"
      }
    ]
  },
  {
    "label": "Posts",
    "items": [{
        "label": "All Posts"
      },
      {
        "label": "New Post"
      },
      {
        "label": "Post Categories"
      }
    ]
  },
  {
    "label": "Sliders"
  },
  {
    "label": "Settings",
    "items": [{
        "label": "General Settings"
      },
      {
        "label": "User",
        "items": [{
            "label": "Your Profile"
          },
          {
            "label": "Edit Profile"
          }
        ]
      },
      {
        "label": "Social Settings"
      },
      {
        "label": "Link Settings"
      }
    ]
  }
];

function find(array, event) {
    if (typeof array != 'undefined') {
      for (let i = 0; i < array.length; i++) {
        if (array[i].label == event.label) return [event.label];
        let a = this.find(array[i].items, event);
        if (a != null) {
          a.unshift(array[i].label);
          return a;
        }
      }
    }
    return null;
}

console.log(find(menuArray, { "label": "Edit Profile" }));