I am trying to split the below array
{
"Base/Brand/0101-color-brand-primary-red": "#fe414d",
"Base/Brand/0106-color-brand-secondary-green": "#00e6c3",
"Base/Brand/0102-color-brand-primary-light-gray": "#eaecf0",
"Base/Brand/0107-color-brand-secondary-black": "#000000",
"Base/Brand/0103-color-brand-primary-white": "#ffffff",
"Base/Brand/0108-color-brand-secondary-dark-gray": "#b4b4b4",
"Base/Brand/0104-color-brand-secondary-blue": "#079fff",
"Base/Light/Extended/Red/0201-color-extended-900-red": "#7f1d1d",
"Base/Brand/0105-color-brand-secondary-yellow": "#ffe63b",
"Base/Light/Extended/Red/0202-color-extended-800-red": "#991b1b"
}
to something like this
{
"Base": {
"Brand": {
"0101-color-brand-primary-red": "#fe414d",
"0106-color-brand-secondary-green": "#00e6c3",
"Light": {
"Extended": {
"Red": {
"0201-color-extended-900-red": "#7f1d1d",
"0202-color-extended-800-red": "#991b1b"
}
}
}
}
}
}
Basically I need to split array by ‘/’ and create nested array
Please help how can I achieve this.
3
Answers
Use
Object.entries
to get all entries in the original object. Usesplit('/')
to get an array of the object path keys in the output. Then usereduce
on that path array to create levels inside the result, until the very last element in the path is reached. At this point, we set the last path element to the required color value.Since the provided structure is a flat (not nested) object of key-value pairs (entries), one could start aggregating the OP’s desired target data-structure by
reduce
ing the source-object’sentries
.The initial value of this outer
reduce
task will be an empty object (literal).The reducer function of the very same task does receive with each iteration the to be aggregated object reference (which in the very beginning is the initial value / the empty object). It also receives the current iteration’s entry which is a key-value pair provided as an array. The
key
actually is the key-path, a string which can be furthersplit
at every occurring slash. Thevalue
is the path-value which has to be assigned as last value of any aggregated (partial) object reference.Thus, one is in need of a second, nested,
reduce
task which does process each of the key-path’ partialkey
values. The initial value will be always the base or root reference of the to be aggregated object. The innerreduce
task does aggregate the receivednode
reference by either accessing an already existing node, or by creating a new (empty node) or by assigning the final path-value to the last created node. It also always does pass this reference as current node into the next iteration step.You can achieve that with a recursive function like the one below :