-5

Say I have an object that looks like this:

const theme = {
  colors: {
    black: 'rgb(15 15 15)',
    grey15: 'rgb(248 248 248)',
    grey30: 'rgb(241 241 241)',
    grey45: 'rgb(180 180 180)',
    grey60: 'rgb(118 118 118)',
    grey75: 'rgb(57 57 57)',
    grey90: 'rgb(26 26 26)',
    white: 'rgb(255 255 255)',
  },
  typography: {
    body: {
      expressive: {
        fontFamily: 'Helvetica Neue',
        fontSize: '14px',
        fontWeight: 400,
        letterSpacing: '0.06em',
        lineHeight: 1.4,
      },
      productive: {
        fontFamily: 'Helvetica Neue',
        fontSize: '16px',
        fontWeight: 450,
        letterSpacing: '0.12em',
        lineHeight: 1.4,
      },
    },
  },
};

I’d like to reduce that down to an array of paths to each keys’ value in dot notation, like this:

[
  'colors',
  'colors.black',
  'colors.grey15',
  'colors.grey30',
  'colors.grey45',
  'colors.grey60',
  'colors.grey75',
  'colors.grey90',
  'colors.white',
  'typography',
  'typography.body',
  'typography.body.expressive',
  'typography.body.expressive.fontFamily',
  'typography.body.expressive.fontSize',
  'typography.body.expressive.fontWeight',
  'typography.body.expressive.letterSpacing',
  'typography.body.expressive.lineHeight',
  'typography.body.productive',
  'typography.body.productive.fontFamily',
  'typography.body.productive.fontSize',
  'typography.body.productive.fontWeight',
  'typography.body.productive.letterSpacing',
  'typography.body.productive.lineHeight',
]

Thoughts on an elegant solution?

Brandon Durham
  • 7,096
  • 13
  • 64
  • 101
  • also [JS: convert array objects to dot string](https://stackoverflow.com/questions/57433293/js-convert-array-objects-to-dot-string) or [Convert complex JavaScript object to dot notation object](https://stackoverflow.com/questions/13218745/convert-complex-javascript-object-to-dot-notation-object) and [Fastest way to flatten / un-flatten nested JavaScript objects](https://stackoverflow.com/questions/19098797/fastest-way-to-flatten-un-flatten-nested-javascript-objects) – pilchard Aug 30 '23 at 21:41

0 Answers0