Skip to content

Instantly share code, notes, and snippets.

@lukekarrys
Last active December 7, 2016 17:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lukekarrys/8e7acddc7ff5bab09851 to your computer and use it in GitHub Desktop.
Save lukekarrys/8e7acddc7ff5bab09851 to your computer and use it in GitHub Desktop.
Get the keys of a nested object in dot notation.

string-keys

import keys from 'string-keys'

keys({
  a: 1,
  b: 2,
  c: null,
  d: {
    e: 1
  },
  e: {
    f: {
      a: [
        {
          b: 1
        },
        {
          b: 2,
          g: null
        }
      ]
    }
  }
})

// ['a', 'b', 'c', 'd.e', 'e.f.a.[0].b', 'e.f.a.[1].b', 'e.f.a.[1].g']
{
"presets": ["es2015"]
}
node_modules/
npm-debug.log
const getKeys = (values, prefix = '', accumulator = []) => {
if (!values) return null;
const isArr = Array.isArray(values);
return Object.keys(values).reduce((memo, key) => {
const value = values[key];
const stringKey = isArr ? `[${key}]` : key;
const nestedKey = prefix ? `${prefix}.${stringKey}` : stringKey;
if (value !== null && typeof value === 'object') {
return getKeys(values[key], nestedKey, memo);
}
return memo.concat(nestedKey);
}, accumulator);
};
export default getKeys;
{
"name": "string-keys",
"description": "Get the keys of a nested object in dot notation.",
"version": "1.0.0",
"author": "Luke Karrys <luke@lukekarrys.com>",
"bugs": {
"url": "https://gist.github.com/lukekarrys/8e7acddc7ff5bab09851"
},
"devDependencies": {
"babel": "^6.3.13",
"babel-preset-es2015": "^6.3.13",
"babel-tape-runner": "^2.0.0",
"tape": "^4.2.2"
},
"homepage": "https://gist.github.com/lukekarrys/8e7acddc7ff5bab09851#file-readme-md",
"keywords": [
"dot",
"keys",
"notation",
"object"
],
"license": "MIT",
"main": "index.js",
"private": true,
"repository": {
"type": "git",
"url": "git@gist.github.com:8e7acddc7ff5bab09851.git"
},
"scripts": {
"test": "babel-tape-runner test.js"
}
}
import test from 'tape';
import keys from './index';
test('Falsy values return null', (t) => {
t.deepEquals(keys(null), null);
t.deepEquals(keys(false), null);
t.end();
});
test('Object works', (t) => {
const obj = {
a: 1,
b: 2,
c: null
};
t.deepEquals(keys(obj), ['a', 'b', 'c']);
t.end();
});
test('Nested object works', (t) => {
const obj = {
a: 1,
b: 2,
c: null,
d: {
a: 1
}
};
t.deepEquals(keys(obj), ['a', 'b', 'c', 'd.a']);
t.end();
});
test('Nested object works', (t) => {
const obj = {
a: 1,
b: 2,
c: undefined,
d: {
a: {
r: 1
}
}
};
t.deepEquals(keys(obj), ['a', 'b', 'c', 'd.a.r']);
t.end();
});
test('Nested object works with an array', (t) => {
const obj = {
a: 1,
b: 2,
c: null,
d: {
e: 1
},
e: {
f: {
a: [
{
b: 1
},
{
b: 2,
g: null
}
]
}
}
};
t.deepEquals(keys(obj), ['a', 'b', 'c', 'd.e', 'e.f.a.[0].b', 'e.f.a.[1].b', 'e.f.a.[1].g']);
t.end();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment