Add flattenObject, unflattenObject

Tagged and tested. Quite complex methods btw.
This commit is contained in:
Angelos Chalaris
2018-02-07 11:30:18 +02:00
parent cc7a7cde7c
commit 3719814f25
8 changed files with 1023 additions and 893 deletions

View File

@ -0,0 +1,12 @@
const flattenObject = (obj, prefix = '') =>
Object.keys(obj).reduce((acc, k) => {
const pre = prefix.length ? (prefix + '.') : '';
if (typeof obj[k] === 'object')
Object.assign(
acc,
flattenObject(obj[k], pre + k)
);
else acc[pre + k] = obj[k];
return acc;
}, {});
module.exports = flattenObject;

View File

@ -0,0 +1,14 @@
const test = require('tape');
const flattenObject = require('./flattenObject.js');
test('Testing flattenObject', (t) => {
//For more information on all the methods supported by tape
//Please go to https://github.com/substack/tape
t.true(typeof flattenObject === 'function', 'flattenObject is a Function');
t.deepEqual(flattenObject({ a: { b: { c: 1 } }, d: 1 }), { 'a.b.c': 1, d: 1 }, 'Flattens an object with the paths for keys');
//t.deepEqual(flattenObject(args..), 'Expected');
//t.equal(flattenObject(args..), 'Expected');
//t.false(flattenObject(args..), 'Expected');
//t.throws(flattenObject(args..), 'Expected');
t.end();
});