• Stars
    star
    1,761
  • Rank 26,443 (Top 0.6 %)
  • Language
    JavaScript
  • License
    BSD 3-Clause "New...
  • Created about 12 years ago
  • Updated 7 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

🚂 Flatten/unflatten nested Javascript objects

flat Build Status

Take a nested Javascript object and flatten it, or unflatten an object with delimited keys.

Installation

$ npm install flat

Methods

flatten(original, options)

Flattens the object - it'll return an object one level deep, regardless of how nested the original object was:

import { flatten } from 'flat'

flatten({
    key1: {
        keyA: 'valueI'
    },
    key2: {
        keyB: 'valueII'
    },
    key3: { a: { b: { c: 2 } } }
})

// {
//   'key1.keyA': 'valueI',
//   'key2.keyB': 'valueII',
//   'key3.a.b.c': 2
// }

unflatten(original, options)

Flattening is reversible too, you can call unflatten on an object:

import { unflatten } from 'flat'

unflatten({
    'three.levels.deep': 42,
    'three.levels': {
        nested: true
    }
})

// {
//     three: {
//         levels: {
//             deep: 42,
//             nested: true
//         }
//     }
// }

Options

delimiter

Use a custom delimiter for (un)flattening your objects, instead of ..

safe

When enabled, both flat and unflatten will preserve arrays and their contents. This is disabled by default.

import { flatten } from 'flat'

flatten({
    this: [
        { contains: 'arrays' },
        { preserving: {
              them: 'for you'
        }}
    ]
}, {
    safe: true
})

// {
//     'this': [
//         { contains: 'arrays' },
//         { preserving: {
//             them: 'for you'
//         }}
//     ]
// }

object

When enabled, arrays will not be created automatically when calling unflatten, like so:

unflatten({
    'hello.you.0': 'ipsum',
    'hello.you.1': 'lorem',
    'hello.other.world': 'foo'
}, { object: true })

// hello: {
//     you: {
//         0: 'ipsum',
//         1: 'lorem',
//     },
//     other: { world: 'foo' }
// }

overwrite

When enabled, existing keys in the unflattened object may be overwritten if they cannot hold a newly encountered nested value:

unflatten({
    'TRAVIS': 'true',
    'TRAVIS.DIR': '/home/travis/build/kvz/environmental'
}, { overwrite: true })

// TRAVIS: {
//     DIR: '/home/travis/build/kvz/environmental'
// }

Without overwrite set to true, the TRAVIS key would already have been set to a string, thus could not accept the nested DIR element.

This only makes sense on ordered arrays, and since we're overwriting data, should be used with care.

maxDepth

Maximum number of nested objects to flatten.

import { flatten } from 'flat'

flatten({
    key1: {
        keyA: 'valueI'
    },
    key2: {
        keyB: 'valueII'
    },
    key3: { a: { b: { c: 2 } } }
}, { maxDepth: 2 })

// {
//   'key1.keyA': 'valueI',
//   'key2.keyB': 'valueII',
//   'key3.a': { b: { c: 2 } }
// }

transformKey

Transform each part of a flat key before and after flattening.

import { flatten, unflatten } from 'flat'

flatten({
    key1: {
        keyA: 'valueI'
    },
    key2: {
        keyB: 'valueII'
    },
    key3: { a: { b: { c: 2 } } }
}, {
    transformKey: function(key){
      return '__' + key + '__';
    }
})

// {
//   '__key1__.__keyA__': 'valueI',
//   '__key2__.__keyB__': 'valueII',
//   '__key3__.__a__.__b__.__c__': 2
// }

unflatten({
      '__key1__.__keyA__': 'valueI',
      '__key2__.__keyB__': 'valueII',
      '__key3__.__a__.__b__.__c__': 2
}, {
    transformKey: function(key){
      return key.substring(2, key.length - 2)
    }
})

// {
//     key1: {
//         keyA: 'valueI'
//     },
//     key2: {
//         keyB: 'valueII'
//     },
//     key3: { a: { b: { c: 2 } } }
// }

Command Line Usage

flat is also available as a command line tool. You can run it with npx:

npx flat foo.json

Or install the flat command globally:

npm i -g flat && flat foo.json

Accepts a filename as an argument:

flat foo.json

Also accepts JSON on stdin:

cat foo.json | flat

More Repositories

1

disc

📈 Visualise the module tree of browserify project bundles and track down bloat.
JavaScript
1,320
star
2

envify

🔧 Selectively replace Node-style environment variables with plain strings.
JavaScript
902
star
3

colony

📈 In-browser network graphs representing the links between your Node.js code and its dependencies.
JavaScript
519
star
4

uglifyify

A browserify transform which minifies your code using UglifyJS2
JavaScript
375
star
5

vinyl-source-stream

🌀 Use conventional text streams at the start of your gulp or vinyl pipelines
JavaScript
333
star
6

glsl-noise

webgl-noise shaders ported to work with glslify
GLSL
326
star
7

smokestack

Pipe your JavaScript into a browser, logging console output in Node
JavaScript
246
star
8

boids

A fast JavaScript implementation of the boids algorithm
JavaScript
214
star
9

web-audio-analyser

A thin wrapper around the Web Audio API that takes an <audio> element and gives you its waveform/frequency data in return.
JavaScript
208
star
10

svg-path-parser

A parser for SVG's path syntax
JavaScript
205
star
11

glsl-dither

Bayer matrix dithering in GLSL
C
181
star
12

game-modules

📗 A list of game-related modules and examples for writing HTML5 games with browserify
170
star
13

from2

Convenience wrapper for ReadableStream, with an API lifted from "from" and "through2"
JavaScript
131
star
14

particle-excess-demo

Simulating and rendering 262,144 particles with GLSL.
JavaScript
128
star
15

matcap

GLSL shaders for calculating/rendering Spherical Environment Maps, or "matcaps"
JavaScript
122
star
16

atom-npm-install

Automatically install and save any missing npm modules being used in the current file
JavaScript
81
star
17

s3-sync

A streaming interface for uploading multiple files to S3.
JavaScript
79
star
18

vinyl-buffer

Convert streaming vinyl files to use buffers
JavaScript
77
star
19

installify

A browserify transform that automatically installs your missing dependencies for you
JavaScript
71
star
20

gif-video

Convert a GIF image into an HTML5-ready video for considerably better file sizes
JavaScript
67
star
21

scene-tree

Modular scene graph for composing and manipulating objects in a 3D scene.
JavaScript
61
star
22

fragment-foundry

🎓 An introduction to fragment shaders and signed distance functions
GLSL
61
star
23

poly-terrain-demo

Proof-of-concept "low-poly" webgl terrain demo
JavaScript
58
star
24

scat

Pipe your javascripts straight into your browser
JavaScript
58
star
25

right-now

Get the quickest, most high-resolution timestamp possible in node or the browser
JavaScript
57
star
26

gl-gif

Quickly and easily generate looping GIFs using WebGL
JavaScript
55
star
27

vinyl-transform

Use standard text transform streams to write fewer gulp plugins
JavaScript
55
star
28

canvas-fit

Small module for fitting a canvas element within the bounds of its parent.
JavaScript
53
star
29

bezier

n-degree Bezier spline interpolation.
JavaScript
52
star
30

npm-stats

Convenience module for getting data from an NPM registry
JavaScript
51
star
31

browser-menu

A browser-friendly implementation of substack's terminal-menu
JavaScript
51
star
32

three-effectcomposer

@alteredq's EffectComposer plugin for three.js ported for use with Browserify
JavaScript
49
star
33

bistre

A command-line tool and module for printing colourful bole logs.
JavaScript
48
star
34

tap-to-start

JavaScript
48
star
35

ludum-dare-27

hurry!
JavaScript
43
star
36

glslify-live

A browserify transform that transparently enables live reloading of your shaders when using glslify.
JavaScript
42
star
37

display-tree

A JavaScript tree implementation designed to be efficiently "flattened" and sorted.
JavaScript
41
star
38

npm-me

Get a list of download counts over the last month for a particular user's packages
JavaScript
40
star
39

map-limit

async.mapLimit's functionality available as a standalone npm module
JavaScript
39
star
40

clamp

Clamp a value between two other values.
JavaScript
39
star
41

adobe-swatch-exchange

Encode/decode color palettes in Adobe's .ase format
JavaScript
38
star
42

beats

A naive but generic beat-detection module
JavaScript
37
star
43

icosphere

Generates icosphere meshes of varying levels of complexity
JavaScript
37
star
44

npm-offline

An npm registry proxy that uses your npm cache to retrieve modules, allowing for offline access to any modules you've previously installed pretty much ever.
JavaScript
37
star
45

vinyl-map

Map vinyl files' contents as strings
JavaScript
36
star
46

ndarray-pixel-sort

A JS implementation of Kim Asendorf's pixel sort glitch technique using ndarrays
JavaScript
36
star
47

komponist

A simple, yet flexible, Node client library for MPD, the hackable headless audio playback server.
JavaScript
36
star
48

png-chunks-extract

🔍 Extract the data chunks from a PNG file.
JavaScript
35
star
49

png-chunk-text

📜 Create or parse a PNG tEXt chunk for storing uncompressed text data in PNG images.
JavaScript
33
star
50

glsl-fog

Basic fog functions for GLSL
C
32
star
51

d3-grid-layout

A grid layout for d3.js
JavaScript
32
star
52

soundcloud-badge

A SoundCloud 'now-playing' badge you can just drop into browserify demos
CSS
31
star
53

topdown-physics

Basic, grid-based, 2D top-down player physics for continuous ndarrays
JavaScript
30
star
54

glsl-luma

Get the luma (brightness) of an RGB color in GLSL. Useful for converting images to greyscale
C
30
star
55

language-glsl

Atom language support for GLSL
GLSL
30
star
56

ansi-html-stream

Stream for converting terminal UTF-8 ANSI color codes into HTML
JavaScript
30
star
57

lsb

Steganography cheap trick - hide string data in the least-significant bits of an array.
JavaScript
27
star
58

post-process

A generic GLSL post-processing module for applying super-speedy GPU effects to img/video/canvas elements.
JavaScript
27
star
59

gulp-duration

Track the duration of parts of your gulp tasks
JavaScript
26
star
60

rm-modules

Recursively remove *all* node_modules directories within the chosen root directory
JavaScript
26
star
61

shallow-equals

Determine if an array or object is equivalent with another, *not* recursively
JavaScript
26
star
62

glsl-hsv2rgb

Fast GLSL conversion from HSV color to RGB
C
26
star
63

font-atlas

Populate a <canvas> element with a font texture atlas
JavaScript
25
star
64

lut

Render RGB lookup tables to a canvas element
JavaScript
24
star
65

flood-fill

A simple 2D JavaScript flood fill.
JavaScript
24
star
66

hypotrochoid

Plot hypotrochoids for spirographs with JavaScript
JavaScript
23
star
67

svg-line-curved

Generate the path attribute for a curved SVG line.
JavaScript
23
star
68

fresh-require

Bypass the require cache when requiring a module – works with both node and browserify
JavaScript
22
star
69

btoa-lite

Smallest/simplest possible means of using btoa with both Node and browserify
JavaScript
22
star
70

scroll-speed

Get the scroll speed being used on either the window or a particular element.
JavaScript
22
star
71

is-typedarray

Detect whether or not an object is a Typed Array
JavaScript
21
star
72

ndarray-continuous

Create continuous "chunked" grids/volumes with ndarrays.
JavaScript
21
star
73

ticker

Game/animation loop helper
JavaScript
21
star
74

vectors

A grab bag of vector utility functions for 2D and 3D vectors that operate on plain arrays
JavaScript
21
star
75

s3-write-stream

Pipe data straight to an S3 key of your choice
JavaScript
21
star
76

plucker

Pluck nested properties from an object
JavaScript
21
star
77

from-3d-to-2d

Take a transformation matrix like you're used to constructing with WebGL, and project arbitrary 3D points onto your 2D screen.
JavaScript
21
star
78

object-pool

Recycle objects with minimal boilerplate with an object pool
JavaScript
20
star
79

png-chunks-encode

💾 Return a fresh PNG buffer given a set of PNG chunks
JavaScript
20
star
80

moire-1

JavaScript
20
star
81

chrome-launch

Light cross-platform launcher for Google Chrome
JavaScript
20
star
82

canvas-orbit-camera

An alternative wrapper for orbit-camera that works independently of game-shell.
JavaScript
20
star
83

canvas-autoscale

A variant of canvas-fit that handles some extra magic for you: adjusting the scale of the canvas to maintain smooth framerates
JavaScript
19
star
84

soundcloud-resolve

Takes a SoundCloud URL and retrieves the relevant JSON data for that resource from the SoundCloud API
JavaScript
19
star
85

svg-line

Generate SVG paths for a line, d3-style
JavaScript
19
star
86

chrome-location

Approximates the current location of Google Chrome on your system
JavaScript
18
star
87

ecosystem-docs

Aggregate and store a collection of data for GitHub repositories, intended for use with documenting package ecosystems on npm
JavaScript
18
star
88

circular-list

Circular linked lists
JavaScript
18
star
89

district

A small tool to help you write local, namespaced packages for larger projects
JavaScript
18
star
90

module-generator

The generator script I use for fresh modules
JavaScript
17
star
91

voxel-glslgen

Push voxel.js terrain generation to the GPU using a GLSL shader
JavaScript
17
star
92

stopmotion

Combine multiple image buffer frames into a video file
JavaScript
16
star
93

tap-closer

Simple JS "transform" tool that will call window.close or process.exit when TAP output is complete
JavaScript
16
star
94

contributor-table

Automatically inject a list of your git repository's contributors into your readme.
JavaScript
16
star
95

frame-debounce

JavaScript
15
star
96

glsl-point-light

A reusable GLSL point light function
JavaScript
15
star
97

glsl-testify

Test your GLSL shaders using GLSL!
JavaScript
15
star
98

github-commit-stream

Pull a list of commits from a GitHub repository in via a stream.
JavaScript
15
star
99

fql-node

Simpler Facebook FQL queries for Node.
JavaScript
14
star
100

common-prefix

Retrieve the common prefix across multiple strings
JavaScript
14
star