Skip to content

Commit 7540bb2

Browse files
fix: nested parent ids did not work if parent was null or undefined
1 parent efe07a8 commit 7540bb2

File tree

2 files changed

+48
-1
lines changed

2 files changed

+48
-1
lines changed

src/arrayToTree.spec.ts

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -495,6 +495,7 @@ describe("arrayToTree", () => {
495495
},
496496
]);
497497
});
498+
498499
it("should work with nested id property", () => {
499500
expect(
500501
arrayToTree(
@@ -516,6 +517,7 @@ describe("arrayToTree", () => {
516517
},
517518
]);
518519
});
520+
519521
it("should work with nested parentId property", () => {
520522
expect(
521523
arrayToTree(
@@ -537,6 +539,7 @@ describe("arrayToTree", () => {
537539
},
538540
]);
539541
});
542+
540543
it("should work with nested id and parentId properties", () => {
541544
expect(
542545
arrayToTree(
@@ -558,4 +561,48 @@ describe("arrayToTree", () => {
558561
},
559562
]);
560563
});
564+
565+
it("should work with nested id and parentId properties if the parent is null", () => {
566+
expect(
567+
arrayToTree(
568+
[
569+
{ one: { id: "1" }, two: null, custom: "1" },
570+
{ one: { id: "1.1" }, two: { parentId: "1" }, custom: "1.1" },
571+
],
572+
{ id: "one.id", parentId: "two.parentId" }
573+
)
574+
).to.deep.equal([
575+
{
576+
data: { one: { id: "1" }, two: null, custom: "1" },
577+
children: [
578+
{
579+
data: { one: { id: "1.1" }, two: { parentId: "1" }, custom: "1.1" },
580+
children: [],
581+
},
582+
],
583+
},
584+
]);
585+
});
586+
587+
it("should work with nested id and parentId properties if the parent is undefined", () => {
588+
expect(
589+
arrayToTree(
590+
[
591+
{ one: { id: "1" }, custom: "1" },
592+
{ one: { id: "1.1" }, two: { parentId: "1" }, custom: "1.1" },
593+
],
594+
{ id: "one.id", parentId: "two.parentId" }
595+
)
596+
).to.deep.equal([
597+
{
598+
data: { one: { id: "1" }, custom: "1" },
599+
children: [
600+
{
601+
data: { one: { id: "1.1" }, two: { parentId: "1" }, custom: "1.1" },
602+
children: [],
603+
},
604+
],
605+
},
606+
]);
607+
});
561608
});

src/arrayToTree.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -140,5 +140,5 @@ export function arrayToTree(
140140
* @param nestedProperty the chained properties to access the nested property. Eg: 'your.nested.property'
141141
*/
142142
function getNestedProperty(item: Item, nestedProperty: string) {
143-
return nestedProperty.split(".").reduce((o, i) => o[i], item);
143+
return nestedProperty.split(".").reduce((o, i) => o && o[i], item);
144144
}

0 commit comments

Comments
 (0)