forked from BlakeGuilloud/ganon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathflattenNestedObject.js
29 lines (22 loc) · 917 Bytes
/
flattenNestedObject.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
const flattenArray = require("./flattenArray");
const getKeyValuePairs = require("./getKeyValuePairs");
const hasNestedProperties = require("./hasNestedProperties");
const isObject = require("./isObject");
// Write function which takes a nested object and flattens it
//
// flattenNestedObject({ "a" : 1, "b" : { "c" : { "d" : { "e" : 1, "f" : 2 } } } }, '-') => {a: 1, "b-c-d-e": 1, "b-c-d-f": 2}
// flattenNestedObject({ "a" : 1, "b" : { "c" : { "d" : { "e" : 1, "f" : 2 } } } }) => {a: 1, "b.c.d.e": 1, "b.c.d.f": 2}
function flattenNestedObject(object, delimiter = ".") {
if (!isObject(object)) {
throw new Error("First parameter must be an object");
}
if (!hasNestedProperties(object)) {
return object;
}
return getKeyValuePairs(object, delimiter).reduce(toObject, {});
}
function toObject(acc, { key, value }) {
acc[key] = value;
return acc;
}
module.exports = flattenNestedObject;