Skip to content

throwIfOrphans: true and input array elements order #18

@lkallas

Description

@lkallas

Consider a tree with 4 elements like this:

{
  "id": "root",
  "parent_id": null,
  "bar": "bar",
  "children": [
    {
      "id": "2",
      "parent_id": "root",
      "foo": "bar",
      "children": []
    },
    {
      "id": "1",
      "parent_id": "root",
      "foo": "bar",
      "children": [
        {
          "id": "1-1",
          "parent_id": "1",
          "foo": "bar",
          "children": []
        }
      ]
    }
  ]
}

As you may see there is multi level nesting in this tree.

When I break this tree into individual elements and try to build it with option throwIfOrphans: true it will throw. It should not, because there are actually no orphans.

This issue comes from the order of items in the array passed into the arrayToTree function.

To reproduce:

const tree = arrayToTree(
  [
    { id: '2', parent_id: 'root', foo: 'bar' },
    { id: '1-1', parent_id: '1', foo: 'bar' },
    { id: '1', parent_id: 'root', foo: 'bar' },
    { id: 'root', parent_id: null, bar: 'bar' },
  ],
  {
    id: 'id',
    parentId: 'parent_id',
    childrenField: 'children',
    dataField: null,
    throwIfOrphans: true,
  },
);

Results:

Error: The items array contains orphans that point to the following parentIds: [1]. These parentIds do not exist in the items array. Hint: prevent orphans to result in an error by passing the following option: { throwIfOrphans: false }

Now when you change the order of elements in the array it will not throw:

const tree = arrayToTree(
  [
    { id: '2', parent_id: 'root', foo: 'bar' },
    { id: '1', parent_id: 'root', foo: 'bar' },
    { id: '1-1', parent_id: '1', foo: 'bar' },
    { id: 'root', parent_id: null, bar: 'bar' },
  ],
  {
    id: 'id',
    parentId: 'parent_id',
    childrenField: 'children',
    dataField: null,
    throwIfOrphans: true,
  },
);

Meaning that the input array order matters. The error is misleading in this particular case.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions