Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add deepKeys() #94

Merged
merged 8 commits into from Feb 17, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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]);
Richienb marked this conversation as resolved.
Show resolved Hide resolved
}

return Object.entries(value);
}

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

for (let [index, segment] of entries(pathSegments)) {
if (typeof segment === 'number') {
result += `[${segment}]`;
Richienb marked this conversation as resolved.
Show resolved Hide resolved
} 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]',
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you want to be extra thorough you could cover the case where an array contains a complex object too, but I imagine it’s fine.

'a\\.b.c.d[1]',
'a\\.b.c.d[2]',
'a\\.b.c.e',
'a\\.b.c.f',
'a\\.b..a',
'.a',
]);
Richienb marked this conversation as resolved.
Show resolved Hide resolved

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