_ _
_ __ | |__ | | ___ __ _
| '_ \| '_ \| |/ _ \ / _` |
| |_) | | | | | (_) | (_| |
| .__/|_| |_|_|\___/ \__, |
|_| ...2019-09-12 |___/
In javascript I found that sometimes it's nice to be able to describe an
object structure in a disconnected way, as a list of paths and values, among
other information, of. Basically this happens when one want in one place to
treat data in a flat manner, but would like a structured representation of that
data in another place.
What I came up with is probably not a unique solution, but I think it has some
elegance to it.
Let's say we have a flat list describing our structure in js:
const theData = [
{ path: 'a.b.c', val: 1 },
{ path: 't', val: 2 },
{ path: 'a.b.d.e', val: 3 },
{ path: 'b.c.d', val: 4 },
];
console.log(JSON.stringify(theData,null,2));
const niceObject = {
a: {
b: {
c: 1,
d: {
e: 3
}
}
},
t: 2,
b: {
c: {
d: 4
}
}
};
console.log(JSON.stringify(niceObject,null,2));
function unpack(keys, value, obj) {
const key = keys.shift();
if(keys.length===0) {
obj[key]=value;
return obj;
} else {
if(obj[key]===undefined) {
obj[key]={};
}
return unpack(keys, value, obj[key]);
}
}
const generatedNiceObject = theData.reduce( (obj, item)=>{
unpack( item.path.split('.'), item.val, obj );
return obj;
}, {});
console.log(JSON.stringify(generatedNiceObject,null,2));
The output looks like this:
[
{
"path": "a.b.c",
"val": 1
},
{
"path": "t",
"val": 2
},
{
"path": "a.b.d.e",
"val": 3
},
{
"path": "b.c.d",
"val": 4
}
]
{
"a": {
"b": {
"c": 1,
"d": {
"e": 3
}
}
},
"t": 2,
"b": {
"c": {
"d": 4
}
}
}
{
"a": {
"b": {
"c": 1,
"d": {
"e": 3
}
}
},
"t": 2,
"b": {
"c": {
"d": 4
}
}
}