Skip to content

Instantly share code, notes, and snippets.

@smugen
Created November 6, 2022 11:44
Show Gist options
  • Save smugen/c27771fa42dc6c0d3038e840d725ce6f to your computer and use it in GitHub Desktop.
Save smugen/c27771fa42dc6c0d3038e840d725ce6f to your computer and use it in GitHub Desktop.
221103 Practice
const SEP = '.';
/**
* traversal an object and flatten its nested objects property keys,
* concatted by a `.` into a single level non-nested object
*
* @param obj object
*
* @returns object
*/
function flattenObject(obj) {
if (typeof obj !== 'object' || obj === null) {
return obj;
}
const flattened = {};
for (let key of Object.keys(obj)) {
const val = obj[key];
if (typeof val !== 'object' || val === null) {
flattened[key] = val;
continue;
}
const expanded = flattenObject(val);
for (let expandedKey of Object.keys(expanded)) {
flattened[[key, expandedKey].join(SEP)] = expanded[expandedKey];
}
}
return flattened;
}
const testee = {
str: 'I am string',
num: 123,
obj: {
a: true,
b: 321,
c: '',
},
obj2: {
x: 666,
obj21: {
i: 'hello',
j: null,
k: 999,
obj211: {
p: undefined,
q: 369
},
obj212: {
r: 'world',
s: 'bye',
},
},
y: 'hi',
obj22: {
d: 246,
obj221: {
m: 'peace',
n: 0xFF,
},
f: 357,
},
z: false,
},
};
console.log('testee', testee);
console.log('flattenObject(testee)', flattenObject(testee));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment