Skip to content

Instantly share code, notes, and snippets.

@albertorestifo
Last active August 2, 2023 10:27
Show Gist options
  • Save albertorestifo/6e6d35b14a11a0a04537 to your computer and use it in GitHub Desktop.
Save albertorestifo/6e6d35b14a11a0a04537 to your computer and use it in GitHub Desktop.
Transform a nested object insto a nested Map object
/**
* 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