JS匹配包含嵌套对象和嵌套数组的数组中的键值

时间:2018-11-09 21:38:19

标签: javascript arrays object

我需要一个高效的函数来提取数组中参数的索引和位置-但是数组可能很复杂。

这是数组:

let root_menu = {
        nav_title: $rootScope.t['General administration'],
        items: [
          { // overview
            title: $rootScope.t['Overview'],
            path: `/root/overview`,
            module: "overview/menu",
            icon: "fa fa-home"
          }, // overview
          { // cardboards
            title: $rootScope.t['Cardboards'],
            path: `/root/cardboards`,
            module: "cardboards/menu",
            icon: "fa fa-files-o",
            subs: [
              {
                title: $rootScope.t['Suppliers'],
                path: `/root/cardboards/suppliers`,
                module: "suppliers/menu",
                icon: "fa fa-handshake-o"
              },
              {
                title: $rootScope.t['Employees'],
                path: `/root/cardboards/employees`,
                module: "employees/menu",
                icon: "fa fa-address-book-o"
              },
            ]
          }, // cardboards
          { // charts
            title: $rootScope.t['Charts'],
            path: `/root/charts`,
            icon: "fa fa-area-chart",
            module: "charts/menu",
            subs: [
              {
                title: $rootScope.t['Activity'],
                path: `/root/charts/activity`,
                module: "charts/activity/menu"
              },
            ]
          }, // charts
          { // settings
            title: $rootScope.t['Settings'],
            path: `/root/settings`,
            module: "settings/menu",
            icon: "fa fa-cogs",
            subs: [
              {
                title: $rootScope.t['Permissions'],
                path: `/root/settings/permissions`,
                module: "settings/permissions/menu",
                icon: "fa fa-file-text-o"
              }
            ]
          } // settings
        ]
      };

现在我有了这个面包屑数组:

["/", "/root", "/root/cardboards", "/root/cardoards/employees", "/root/cardboards/employees/123"]

我想将面包屑数组中的每个键(如果有的话)都匹配到第一个数组,所以我可以得到这样的东西:

[
 {path: "/root/cardboards/", title: "the title from the first 
 array"},
 {path: "/root/cardboards/employees", title: "the title from the . 
 first array"}
]

如您所见,如果第二个数组与第一个数组之间没有匹配项(在路径键下),则不应将新数组附加到附件上。

如何有效地做到这一点-使用ES6更好。

1 个答案:

答案 0 :(得分:0)

一种解决方案是创建从路径到其对象的映射。但是要做到这一点,您需要递归地遍历Insert into Car (ID, Manufacturer, Model, Colour, DateOfRegistration,NumberPlate, [4x4], MotExpiry) Values (1000001, 'Nissan', 'XTrail','Green', getdate(), 'EK64 XEJ', 1, '2018-11-26') 数组。一旦有了该索引/映射,就可以通过访问映射中该路径键的值来轻松获得路径的标题:

items