Skip to content

Commit d64b8d9

Browse files
committed
fix: setting nested array object properties should not be replaced, but merged
1 parent 439a024 commit d64b8d9

File tree

2 files changed

+28
-2
lines changed

2 files changed

+28
-2
lines changed

lib/set.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -61,8 +61,9 @@ function addValue(data, key, value) {
6161
}
6262

6363
function create(data, key, isArray) {
64-
if (data[key] != null) {
65-
return data[key];
64+
const property = key.match(arrayIndex)?.pop() ?? key;
65+
if (data[property] != null) {
66+
return data[property];
6667
}
6768
const value = isArray ? [] : {};
6869
addValue(data, key, value);

test/unit/set.test.ts

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,31 @@ describe("pointer.set", () => {
102102
expect(result.array[1].valid).to.be.true;
103103
});
104104

105+
it("should add property to object in array", () => {
106+
const result = set<{ array?: Array<any> }>(
107+
{ array: ["first", { id: 123 }] },
108+
"/array/[1]/valid",
109+
true
110+
);
111+
112+
expect(result.array.length).to.eq(2);
113+
expect(result.array[0]).to.equal("first");
114+
expect(result.array[1]).to.deep.equal({ id: 123, valid: true });
115+
});
116+
117+
it("should append object in array", () => {
118+
const result = set<{ array?: Array<any> }>(
119+
{ array: ["first", { id: 123 }] },
120+
"/array/[]/valid",
121+
true
122+
);
123+
124+
expect(result.array.length).to.eq(3);
125+
expect(result.array[0]).to.equal("first");
126+
expect(result.array[1]).to.deep.equal({ id: 123 });
127+
expect(result.array[2]).to.deep.equal({ valid: true });
128+
});
129+
105130
it("should accept a list of properties as pointer", () => {
106131
const result = set<{ array?: Array<any> }>(
107132
{},

0 commit comments

Comments
 (0)