Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

flat

Package Overview
Dependencies
Maintainers
1
Versions
28
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

flat - npm Package Compare versions

Comparing version 0.2.0 to 1.0.0

48

index.js

@@ -34,33 +34,41 @@ var flat = module.exports = {}

var unflatten = flat.unflatten = function (target, opts) {
if (typeof target !== 'object') return target
var opts = opts || {}
, delimiter = opts.delimiter || '.'
, result = {}
if (opts.safe && Array.isArray(target)) {
return target.map(function(value) {
return unflatten(value, opts);
});
if (Object.prototype.toString.call(target) !== '[object Object]') {
return target
}
target = flatten(target, opts)
function getkey(key) {
var parsedKey = parseInt(key)
return (isNaN(parsedKey) ? key : parsedKey)
};
var unflat = Object.keys(target).reduce(function (memo, key) {
Object.keys(target).forEach(function(key) {
var split = key.split(delimiter)
, first = split.shift()
, firstNibble
, secondNibble
, recipient = result
if (split.length < 1) {
memo[key] = target[key]
return memo
}
firstNibble = getkey(split.shift())
secondNibble = getkey(split[0])
memo[first] = memo[first] || {}
memo[first][split.join(delimiter)] = target[key]
while (secondNibble !== undefined) {
if (recipient[firstNibble] === undefined) {
recipient[firstNibble] = ((typeof secondNibble === 'number') ? [] : {})
}
memo[first] = unflatten(memo[first], opts)
recipient = recipient[firstNibble]
if (split.length > 0) {
firstNibble = getkey(split.shift())
secondNibble = getkey(split[0])
}
}
return memo;
}, {})
// unflatten again for 'messy objects'
recipient[firstNibble] = unflatten(target[key])
});
return unflat
};
return result
};
{
"name": "flat",
"version": "0.2.0",
"version": "1.0.0",
"main": "index.js",

@@ -5,0 +5,0 @@ "scripts": {

@@ -234,2 +234,18 @@ var assert = require('assert')

})
})
});
suite('Arrays', function() {
var object, flatObject;
object = { "a": ["foo", "bar"] };
flatObject = { "a.0": "foo", "a.1": "bar"};
test('Should be able to flatten arrays properly', function() {
assert.deepEqual(flatObject, flatten(object));
});
test('Should be able to revert and reverse array serialization via unflatten', function() {
assert.deepEqual(object, unflatten(flatObject));
});
test('Array typed objects should be restored by unflatten', function () {
assert.equal(Object.prototype.toString.call(object.a), Object.prototype.toString.call(unflatten(flatObject).a));
})
});
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc