根据 Id 和 ParentId 重构具有嵌套对象的数组。根据属性删除空

问题描述 投票:0回答:1

我有一个平面数组,我根据子级的parentFolderId 嵌套在一起。我需要删除所有子项或其下面的子项都不包含属性 in_shop

的项目

我的示例数据如下所示:

const menuItems = [
  {
    id: 1,
    displayName: "Equipment",
    parentFolderId: null,
    // ... rest of object
  },
    {
    id: 2,
    displayName: "Equipment",
    parentFolderId: 6,
    // ... rest of object
  },
    {
    id: 3,
    displayName: "Equipment",
    parentFolderId: 2,
    in_shop: true
    // ... rest of object
  }, 
    {
    id: 4,
    displayName: "Equipment",
    parentFolderId: 1,
    // ... rest of object
  },
    {
    id: 5,
    displayName: "Equipment",
    parentFolderId: 1,
    // ... rest of object
  },
    {
    id: 6,
    displayName: "Equipment",
    parentFolderId: null,
    // ... rest of object
  },
    {
    id: 7,
    displayName: "Equipment",
    parentFolderId: 5,
    in_shop: true,
    // ... rest of object
  },
    {
    id: 8,
    displayName: "Equipment",
    parentFolderId: 3,
    // ... rest of object
  },
  // ... rest of objects
];

我想要一个看起来像这样的结果,基于上面的输入:

const menuItems = [
  {
    id: 1,
    displayName: "Equipment",
    parentFolderId: null,
    // ... rest of object
    children: [
      {
        id: 5,
        displayName: "Equipment",
        parentFolderId: 1,
        children: [
          {
            id: 7,
            displayName: "Equipment",
            parentFolderId: 5,
            in_shop: true,
            // ... rest of object
          },
        ]
        // ... rest of object
      },
    ],
  },

  {
    id: 6,
    displayName: "Equipment",
    parentFolderId: null,
    // ... rest of object
    children: [
      {
        id: 2,
        displayName: "Equipment",
        parentFolderId: 6,
        // ... rest of object
        children: [
          {
            id: 3,
            displayName: "Equipment",
            parentFolderId: 2,
            in_shop: true,
            // ... rest of object
          },
        ],
      },
    ],
  },
  // ... rest of objects
]

我无法理解如何从数组底部递归循环,然后返回。

我的在子项下对数组进行排序的代码如下所示:

function addChild(obj) {
    // get children and further retrieve its children with map recursively
    let children = menuItems.filter(a => a.parentFolderId == obj.id).map(addChild)

    // if children are found then add childs in object ALso check if item is in shop
    if (children.length > 0 ) {
      return { ...obj, children }
    }

    // if no children found then return object only
    return { ...obj }
  }
const result = menuItems.filter(a => a.parentFolderId == null).map(addChild)
javascript arrays javascript-objects
1个回答
0
投票

更新返回值如下:

return { ...obj, children, in_shop: obj.in_shop || children.some(child => child.in_shop) }
© www.soinside.com 2019 - 2024. All rights reserved.