Skip to content

Commit

Permalink
Add deepKeys() (#94)
Browse files Browse the repository at this point in the history
  • Loading branch information
Richienb committed Feb 17, 2022
1 parent 2c1bbfb commit 3902c64
Show file tree
Hide file tree
Showing 5 changed files with 132 additions and 2 deletions.
27 changes: 27 additions & 0 deletions index.d.ts
Expand Up @@ -131,3 +131,30 @@ console.log(getProperty(object, escapedPath));
```
*/
export function escapePath(path: string): string;

/**
Returns an array of every path. Plain objects are deeply recursed and are not themselves included.
This can be useful to help flatten an object for an API that only accepts key-value pairs or for a tagged template literal.
@param object - The object to iterate through.
@example
```
import {getProperty, deepKeys} from 'dot-prop';
const user = {
name: {
first: 'Richie',
last: 'Bendall',
},
};
for (const property of deepKeys(user)) {
console.log(`${property}: ${getProperty(user, property)}`);
//=> name.first: Richie
//=> name.last: Bendall
}
```
*/
export function deepKeys(object: unknown): string[];
42 changes: 42 additions & 0 deletions index.js
Expand Up @@ -284,3 +284,45 @@ export function escapePath(path) {

return path.replace(/[\\.[]/g, '\\$&');
}

// The keys returned by Object.entries() for arrays are strings
function entries(value) {
if (Array.isArray(value)) {
return value.map((value, index) => [index, value]);
}

return Object.entries(value);
}

function stringifyPath(pathSegments) {
let result = '';

for (let [index, segment] of entries(pathSegments)) {
if (typeof segment === 'number') {
result += `[${segment}]`;
} else {
segment = escapePath(segment);
result += index === 0 ? segment : `.${segment}`;
}
}

return result;
}

function * deepKeysIterator(object, currentPath = []) {
if (!isObject(object)) {
if (currentPath.length > 0) {
yield stringifyPath(currentPath);
}

return;
}

for (const [key, value] of entries(object)) {
yield * deepKeysIterator(value, [...currentPath, key]);
}
}

export function deepKeys(object) {
return [...deepKeysIterator(object)];
}
4 changes: 3 additions & 1 deletion index.test-d.ts
@@ -1,5 +1,5 @@
import {expectTypeOf} from 'expect-type';
import {getProperty, setProperty, hasProperty, deleteProperty} from './index.js';
import {getProperty, setProperty, hasProperty, deleteProperty, deepKeys} from './index.js';

expectTypeOf(getProperty({foo: {bar: 'unicorn'}}, 'foo.bar')).toBeString();
expectTypeOf(getProperty({foo: {bar: 'a'}}, 'foo.notDefined.deep')).toBeUndefined();
Expand All @@ -17,3 +17,5 @@ expectTypeOf(setProperty(object, 'foo.bar', 'b')).toEqualTypeOf(object);
expectTypeOf(hasProperty({foo: {bar: 'unicorn'}}, 'foo.bar')).toEqualTypeOf<boolean>();

expectTypeOf(deleteProperty({foo: {bar: 'a'}}, 'foo.bar')).toEqualTypeOf<boolean>();

expectTypeOf(deepKeys({foo: {bar: 'a'}})).toEqualTypeOf<string[]>();
23 changes: 23 additions & 0 deletions readme.md
Expand Up @@ -108,6 +108,29 @@ console.log(getProperty(object, escapedPath));
//=> '🍄 The princess is in another castle!'
```

### deepKeys(object)

Returns an array of every path. Plain objects are deeply recursed and are not themselves included.

This can be useful to help flatten an object for an API that only accepts key-value pairs or for a tagged template literal.

```js
import {getProperty, deepKeys} from 'dot-prop';

const user = {
name: {
first: 'Richie',
last: 'Bendall',
},
};

for (const property of deepKeys(user)) {
console.log(`${property}: ${getProperty(user, property)}`);
//=> name.first: Richie
//=> name.last: Bendall
}
```

#### object

Type: `object | array`
Expand Down
38 changes: 37 additions & 1 deletion test.js
@@ -1,5 +1,5 @@
import test from 'ava';
import {getProperty, setProperty, hasProperty, deleteProperty, escapePath} from './index.js';
import {getProperty, setProperty, hasProperty, deleteProperty, escapePath, deepKeys} from './index.js';

test('getProperty', t => {
const fixture1 = {foo: {bar: 1}};
Expand Down Expand Up @@ -407,6 +407,42 @@ test('escapePath', t => {
});
});

test('deepKeys', t => {
const object = {
'a.b': {
c: {
d: [1, 2, 3],
e: '🦄',
f: 0,
},
'': {
a: 0,
},
},
'': {
a: 0,
},
};
const keys = deepKeys(object);

t.deepEqual(keys, [
'a\\.b.c.d[0]',
'a\\.b.c.d[1]',
'a\\.b.c.d[2]',
'a\\.b.c.e',
'a\\.b.c.f',
'a\\.b..a',
'.a',
]);

for (const key of keys) {
t.true(hasProperty(object, key));
}

t.deepEqual(deepKeys([]), []);
t.deepEqual(deepKeys(0), []);
});

test('prevent setting/getting `__proto__`', t => {
setProperty({}, '__proto__.unicorn', '🦄');
t.not({}.unicorn, '🦄'); // eslint-disable-line no-use-extend-native/no-use-extend-native
Expand Down

0 comments on commit 3902c64

Please sign in to comment.