Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
186
rated 0 times [  193] [ 7]  / answers: 1 / hits: 155664  / 8 Years ago, wed, may 25, 2016, 12:00:00

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.


More From » arrays

 Answers
12

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);




[#62034] Monday, May 23, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
keyonna

Total Points: 521
Total Questions: 104
Total Answers: 96

Location: Samoa
Member since Tue, May 3, 2022
2 Years ago
keyonna questions
;