Last active
August 2, 2023 10:27
-
-
Save albertorestifo/6e6d35b14a11a0a04537 to your computer and use it in GitHub Desktop.
Transform a nested object insto a nested Map object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Populate a map with the values of an object with nested maps | |
* | |
* @param {Map} map - Map to populate | |
* @param {object} object - Object to use for the population | |
* @param {array} keys - Array of keys of the object | |
* | |
* @return {Map} Populated map | |
*/ | |
function populateMap (map, object, keys) { | |
// Return the map once all the keys have been populated | |
if (!keys.length) return map | |
let key = keys.shift() | |
let value = object[key] | |
if (typeof value === 'object') { | |
// When value is an object, we transform every key of it into a map | |
value = populateMap(new Map(), value, Object.keys(value)) | |
} | |
// Set the value into the map | |
map.set(key, value) | |
// Recursive call | |
return populateMap(map, object, keys) | |
} | |
/** | |
* Example usage: | |
*/ | |
let myMap = new Map() | |
let myObject = { | |
a: { b: 1, c: 2 } | |
} | |
populateMap(myMap, myObject, Object.keys(myObject)) | |
// that is the equivalent of doing: | |
let a = new Map() | |
a.add(b, 1) | |
a.add(c, 2) | |
myMap.add('a', a) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment