Skip to content

null/undefined exception with nested id and parentId properties #38

@IMilja

Description

@IMilja

Hi there,
I've tried to use this library for constructing a tree on a application I'm developing and while it has the awesome feature of using nested id and parentId properties I've noticed a potential bug on it.

The data that I'm getting from an API has the following structure:

var performantArrayToTree = require("performant-array-to-tree");

const data = [
  {
    id: 1,
    title: "Some title",
    parent: null
  },
  {
    id: 125,
    title: "Some title 2",
    parent: {
      id: 1,
    },
  },
];

console.log(performantArrayToTree.arrayToTree(data, {
    parentId: 'parent.id',
}));

Expected result:

[
  {
    data: { id: 1, title: "Some title", parent: null },
    children: [
      {
        data: { id: 125, title: "Some title 2", parent: null },
        children: [],
      }
    ]
  }
]

Result I've gotten:
TypeError: Cannot read property 'parentId' of null

My guess is that the problem is in the following function:

function getNestedProperty(item: Item, nestedProperty: string) {
  return nestedProperty.split(".").reduce((o, i) => o[i], item);
}

Since it's accessing the object o which in my case is null with the key of i it will throw an exception. A potential fix is to check if o is null or undefined and if it is the reduce function should return null as well.

function getNestedProperty(item: Item, nestedProperty: string) {
  return nestedProperty.split(".").reduce((o, i) => (o === null || o === undefined) ? null : o[i], item);
}

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