object-flatten
Flatten a nested object based on a predicate function. The keys are rewritten to path.to.nested.object
.
Install
$ npm install --save object-flatten
Example
See test/index.js for full examples.
const flattened =
This returns you a flattened object:
'margin.auto': marginLeft: 'auto' marginRight: 'auto'
Usage
obj = flattenObject(predicate, obj)
Default export Returns a flattened object.
predicate
A function which decides when to stop flattening. It is invoked on each property in the object with the signatureproperty => true|false
.
isLast
Predicate function which flattens until the deepest object.
// { 'some.very.deep: { prop: true } }
isNotObject
Predicate function which flattens as deep as possible.
// { 'some.very.deep.prop': true } }
Advanced Use Case
The main use case I had in mind, is together with unistyle. Let's say we have a positions.js
module which contains:
relative: position: 'relative' absolute: position: 'absolute' fixed: position: 'fixed' top0: top: 0 bottom0: bottom: 0 left0: left: 0 right0: right: 0 zindex: 'index should be between 1 and 4' zIndex: 1 zIndex: 2 zIndex: 3 zIndex: 4
Then you can use this with your preferred virtual dom library and cngen:
const Container = { return <div class=> children </div> }
The problem comes in when you want to generate your css with this sort of structure. What you have to do is to flatten the object manually:
...positions ...positionszindex
Now imagine that this structure can be even more deep and the manual flattening becomes unmaintainable. This is where object-flatten
helps:
...
Run Tests
$ npm test