JSFiddle - React, Tailwind, and code Playground
JavaScript
const name = "Header/H1"
function walkObject(obj, newValue, isKey = false) {
const keys = Object.keys(obj)
// If it's the top level, create first param
if(keys.length === 0) {
obj[newValue] = {}
}
// Loop through objects parameters
keys.forEach(function(key, i) {
// Only do the first for perf reasons
if (i === 0) {
let value = obj[key];
// If it's an object, recursively run again
if (typeof value === 'object') {
walkObject(value, newValue, isKey);
}
// Set param or value of nested object
if (isKey) {
value[newValue] = {}
} else {
value = newValue
}
}
});
return obj
}
const colorArray = name.split("/")
const colorNameReducer = (accumulator, currentValue, index) => {
if (index == colorArray.length) {
return walkObject(accumulator, "")
}
console.log('creating param', accumulator, currentValue)
return walkObject(accumulator, currentValue, true)
}
const colorObject = colorArray.reduce(colorNameReducer, {});
console.log('colorObject', colorObject)