Solución
solution.tsTypeScript
function flattenObject(obj: Record<string, unknown>, prefix = ""): Record<string, unknown> {
const keys = Object.keys(obj);
if (keys.length == 0) return {};
const flatObject: Record<string, unknown> = {}
processLeaveValue(obj, flatObject, []);
return flatObject;
}
function processLeaveValue(currentValue: unknown, flatObject: Record<string, unknown>, composedKey: string[] = [] ){
if (typeof currentValue != "object"){
flatObject[composedKey.join(".")]= currentValue;
return true;
}
const keys = Object.keys(currentValue);
if(!keys || ! keys.length){
if (composedKey.length == 0){
return true;
}else{
flatObject[composedKey.join(".")]= currentValue;
return true
}
}
keys.forEach((currentKey, index) => {
composedKey.push(currentKey);
console.log(composedKey, currentKey)
const valueWasAdded = processLeaveValue(currentValue[currentKey], flatObject, composedKey)
if(valueWasAdded){
composedKey.pop()
}
if(index === (keys.length-1)){
composedKey.shift();
}
})
}
// No modificar: necesario para evaluar el resultado.
export { flattenObject };0respuestas