Created
February 12, 2016 15:09
-
-
Save faceleg/ef6e36d59cb57cdde903 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head> | |
<meta charset="UTF-8"> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.3.0/lodash.min.js"></script> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.2.5/mocha.js"></script> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/chai/2.3.0/chai.js"></script> | |
<script src="https://cdn.rawgit.com/spalger/WebConsole-reporter/57579baebea6e326effca37745f909c029fcca72/WebConsole.js"></script> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.js"></script> | |
<script src="https://cdn.rawgit.com/spalger/b57619d9d298556ab5e9/raw/af6707d928e22e9c9602f391bb1f238743895632/test.js"></script> | |
</head> | |
<body> | |
<pre>Output is sent to the console.</pre> | |
<script type="text/babel"> | |
/** | |
* Flattens a deeply nested object, `source`. Produces `output` which | |
* will be an object with dot-seperated paths pointing to all primative | |
* values from the `source`. | |
* | |
* Examples: | |
* | |
* flatten({ foo: { bar: 1 } }) | |
* //=> { 'foo.bar': 1 } | |
* | |
* flatten({ foo: [{ bar: 1 }, { bar: 2 }] }) | |
* //=> { 'foo.0.bar': 1, 'foo.1.bar': 2 } | |
* | |
* @param source {object} | |
* @returns {object} | |
*/ | |
window.flatten = function (source, currentKey, keysInPath, accumulator) { | |
if (!accumulator) { | |
accumulator = {} | |
Object.keys(source).forEach(function(key) { | |
flatten(source[key], key, [], accumulator) | |
}) | |
return accumulator | |
} | |
keysInPath.push(currentKey); | |
if (!_.isObject(source)) { | |
accumulator[keysInPath.join('.')] = source | |
} | |
if (_.isObject(source) || _.isArray(source)) { | |
Object.keys(source).forEach(function(key) { | |
flatten(source[key], key, _.clone(keysInPath), accumulator, true) | |
}) | |
} | |
} | |
console.log('Test against https://gist.github.com/epixa/b01490f4fd566498bc5d', _.isEqual(flatten({ | |
a : 1, | |
b: { | |
c: true, | |
d: { | |
e: 'something' | |
} | |
}, | |
f: false, | |
g: ['red', 'green', 'blue'] | |
}), { | |
a: 1, | |
'b.c': true, | |
'b.d.e': 'something', | |
f: false, | |
'g.0': 'red', | |
'g.1': 'green', | |
'g.2': 'blue' | |
})) | |
// run the tests | |
mocha.run(); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment