Algorithmsmedium

Flatten nested object keys into dot paths

Given a nested object, return a flat object where keys are dot-separated paths. Arrays should use numeric indices in the path.

Asked at Amazon, Stripe, Uber

#recursion#objects#data transformation

Answer

function flattenObject(input) {
  const out = {}

  function walk(value, path) {
    if (value === null || typeof value !== 'object') {
      out[path] = value
      return
    }

    if (Array.isArray(value)) {
      if (value.length === 0) out[path] = []
      value.forEach((item, i) => {
        const next = path ? `${path}.${i}` : String(i)
        walk(item, next)
      })
      return
    }

    const keys = Object.keys(value)
    if (keys.length === 0 && path) out[path] = {}
    for (const key of keys) {
      const next = path ? `${path}.${key}` : key
      walk(value[key], next)
    }
  }

  walk(input, '')
  return out
}

// Usage
flattenObject({
  user: { name: 'Ana', address: { city: 'TLV' } },
  tags: ['a', 'b']
})
// {
//   "user.name": "Ana",
//   "user.address.city": "TLV",
//   "tags.0": "a",
//   "tags.1": "b"
// }

Practise more Algorithms questions →