Skip to content

Instantly share code, notes, and snippets.

@carefree-ladka
Created May 17, 2024 12:23
Show Gist options
  • Select an option

  • Save carefree-ladka/5b4a25b227d658a8ada63a5ff8bba2b1 to your computer and use it in GitHub Desktop.

Select an option

Save carefree-ladka/5b4a25b227d658a8ada63a5ff8bba2b1 to your computer and use it in GitHub Desktop.
Object flatten in JS
const getAllKeys = (obj) => {
const result = [];
const queue = [{ path: [], obj }];
while (queue.length) {
const { path, obj: currentObj } = queue.shift();
for (const [key, value] of Object.entries(currentObj)) {
const newPath = path.concat(key);
if (typeof value === 'object' && value !== null) {
queue.push({ path: newPath, obj: value });
}
result.push(newPath.join('.'));
}
}
console.log(result);
return result;
}
const obj = {
a: 1,
b: {
c: 4,
d: {
e: 6,
f: {
g: 10
}
}
}
};
getAllKeys(obj);
//[ 'a', 'b', 'b.c', 'b.d', 'b.d.e', 'b.d.f', 'b.d.f.g' ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment