nixgadgets nixgadgets - 6 months ago 18
JSON Question

Convert Map to JSON object in Javascript

So Ive got the following javascript which contains a key/value pair to map a nested path to a directory.

function createPaths(aliases, propName, path) {
aliases.set(propName, path);
}

map = new Map();

createPaths(map, 'paths.aliases.server.entry', 'src/test');
createPaths(map, 'paths.aliases.dist.entry', 'dist/test');


Now what I want to do is create a JSON object from the key in the map.

It has to be,

paths: {
aliases: {
server: {
entry: 'src/test'
},
dist: {
entry: 'dist/test'
}
}
}


Not sure if there is an out of a box way to do this. Any help is appreciated.

Answer

You could loop over the map and over the keys and assign the value

function createPaths(aliases, propName, path) {
    aliases.set(propName, path);
}

var map = new Map(),
    object = {};

createPaths(map, 'paths.aliases.server.entry', 'src/test');
createPaths(map, 'paths.aliases.dist.entry', 'dist/test');

map.forEach((value, key) => {
    var keys = key.split('.'),
        last = keys.pop();
    keys.reduce((r, a) => r[a] = r[a] || {}, object)[last] = value;
});

console.log(object);