Convert Map To JSON Object In Javascript
Answer :
Given in MDN, fromEntries()
is available since Node v12:
const map1 = new Map([
['foo', 'bar'],
['baz', 42]
]);
const obj = Object.fromEntries(map1);
// { foo: 'bar', baz: 42 }
For converting object back to map:
const map2 = new Map(Object.entries(obj));
// Map(2) { 'foo' => 'bar', 'baz' => 42 }
I hope this function is self-explanatory enough. This is what I used to do the job.
/*
* Turn the map<String, Object> to an Object so it can be converted to JSON
*/
function mapToObj(inputMap) {
let obj = {};
inputMap.forEach(function(value, key){
obj[key] = value
});
return obj;
}
JSON.stringify(returnedObject)
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);
Comments
Post a Comment