Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

safe-flat

jessie-codes576.1kMIT2.1.0TypeScript support: included

Safely flatten a nested JavaScript object.

flat, flatten, json, nested, object, safe, serialize, unflatten

readme

safe-flat

Safely flatten a nested JavaScript object.

NPM

Commitizen friendly js-standard-style Build Coverage Known Vulnerabilities

Installation

$ npm i safe-flat

Methods

flatten(obj, [delimiter])

Flattens an object to one level deep. Optionally takes a custom delimiter, otherwise uses . by default. Circular references within the object will be replaced with [Circular].

const { flatten } = require('safe-flat')

const original = {
    a: {
        b: {
            c: [{
                val: 'one'
            }, {
                val: 'two'
            }],
            d: 'three'
        },
        e: 'four',
    }
}
original.a.b.f = original.a.b
original.a.b.c.push(original.a)

const flat = flatten(original)
/*
{
  'a.b.c.0.val': 'one',
  'a.b.c.1.val': 'two',
  'a.b.c.2': '[Circular]',
  'a.b.d': 'three',
  'a.e': 'four',
  'a.b.f': '[Circular]'
}
*/

const underscoreFlat = flatten(original, '_')
/*
{
  'a_b_c_0_val': 'one',
  'a_b_c_1_val': 'two',
  'a_b_c_2': '[Circular]',
  'a_b_d': 'three',
  'a_e': 'four',
  'a_b_f': '[Circular]'
}
*/

unflatten(obj, [delimiter])

Unflattens an object back to its original nested form. Optionally takes a custom delimiter, otherwise uses . by default. Circular references denoted by [Circular] are treated as Strings.

const { unflatten } = require('safe-flat')

const original = {
    'a.b.c.0.val': 'one',
    'a.b.c.1.val': 'two',
    'a.b.c.2': '[Circular]',
    'a.b.d': 'three',
    'a.e': 'four',
    'a.b.f': '[Circular]'
}


const unflat = unflatten(original)

/*{
  a:{
    b:{
      c:[
        {
          val:'one'
        },
        {
          val:'two'
        },
        '[Circular]'
      ],
      d:'three',
      f:'[Circular]'
    },
    e:'four'
  }
}*/

changelog

2.1.0 (2023-11-30)

Features

  • Adds type definitions to both flatten and unflatten fns. (4618622), closes #50

2.0.3 (2023-11-30)

2.0.2 (2021-01-24)

Bug Fixes

  • unflat: fix potential for prototype pollution (4b9b7db)

2.0.1 (2020-12-31)

Bug Fixes

  • flatten: added support for empty objects (e9b5a5b), closes #39
  • flatten: fixed flatten not handling empty arrays (25b0ffe), closes #39
  • flatten: fixes flatten borking a completely empty object (495e9e3)

2.0.0 (2020-10-06)

Features

  • add an unflatten function that will take a flattened object and return a nested object (cc7c6ef), closes #32

BREAKING CHANGES

  • New version now exports an object containing flatten and unflatten functions

1.1.4 (2020-09-12)

1.1.3 (2020-09-12)

1.1.1 (2019-10-12)

Bug Fixes

1.1.0 (2019-10-09)

1.0.1 (2019-05-03)

1.0.0 (2019-04-22)

Bug Fixes

  • package.json: Fix lint command (0be14b9)

Features