Skip to content

Commit 439a024

Browse files
committed
docs: describe set array behaviour
1 parent 6004380 commit 439a024

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

README.md

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,29 @@ const data = pointer.set({}, ['list', '[]', 'value'], 42);
117117
console.log(data); // output: { list: [ { value: 42 } ] }
118118
```
119119

120+
#### array
121+
122+
Per default `set` creates objects for each each missing data. Thus, a pointer to `/list/1` will create an object with `{ list: { 1: {} } }`. If you want to specify array-data you will need to wrap the array-index in array-brackets:
123+
124+
```ts
125+
pointer.set({}, '/list/[1]', 42);
126+
// { list: [, 42] }
127+
```
128+
129+
Omitting the index from the array-brackets will **append** the item:
130+
131+
```ts
132+
pointer.set({}, '/list/[]', 42);
133+
// { list: [42] }
134+
```
135+
136+
which also works for existing lists:
137+
138+
```ts
139+
pointer.set({ list: ["first"] }, '/list/[]', 42);
140+
// { list: ["first", 42] }
141+
```
142+
120143

121144
### remove
122145

test/unit/set.test.ts

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,13 @@ describe("pointer.set", () => {
6969
expect(result.array[1]).to.be.true;
7070
});
7171

72+
it("should append item to array", () => {
73+
const result = set<{ array?: Array<any> }>({ array: ["first"] }, "/array/[]", "next");
74+
75+
expect(result.array).to.be.an("array");
76+
expect(result.array).to.deep.equal(["first", "next"])
77+
});
78+
7279
it("should insert array in array", () => {
7380
const result = set<{ array?: Array<any> }>({}, "/array/[]/[]", true);
7481

@@ -124,7 +131,6 @@ describe("pointer.set", () => {
124131
"#/array/[1]/valid",
125132
true
126133
);
127-
128134
expect(result.array.length).to.eq(2);
129135
expect(result.array[1]).to.be.an("object");
130136
expect(result.array[1].valid).to.be.true;

0 commit comments

Comments
 (0)