Skip to content

Instantly share code, notes, and snippets.

@glued
Created July 24, 2020 03:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save glued/db2ada725c52c97a6ea8b27e48f1659c to your computer and use it in GitHub Desktop.
Save glued/db2ada725c52c97a6ea8b27e48f1659c to your computer and use it in GitHub Desktop.
Flatten Object
const data = ['foo', 'bar', 'baz'];
const data2 = {
foo: {
bar: 123,
baz: [
{ title: 'foo', value: 'bar' },
{ title: 'a', value: 'a' },
{ title: 'b', value: 'b' },
],
},
movies: [
{ title: 'Test', date: 1234, value: 'foo' },
{ title: 'Test2', value: 'test2' },
{ title: 'Test3', value: 'test3' },
{ title: 'Test4', value: 'test4' },
],
};
const shapedValue = [
{ id: 'foo', title: 'foo', type: 'object', level: 0 },
{ id: 'foo.bar', title: 'bar', type: 'number', value: '123', level: 1 },
//
{ id: 'foo.baz', title: 'baz', type: 'array', level: 1 },
//
{ id: 'foo.baz[0]', title: '0', type: 'object', level: 2 },
{ id: 'foo.baz[0].title', title: 'title', value: 'foo', level: 3 },
{ id: 'foo.baz[0].value', title: 'value', value: 'bar', level: 3 },
///
{ id: 'foo.baz[1]', title: '1', type: 'object', level: 2 },
{ id: 'foo.baz[1].title', title: 'a', value: 'a', level: 3 },
{ id: 'foo.baz[1].value', title: 'a', value: 'a', level: 3 },
];
// data2.foo.baz[0].value
const flattenObject = (obj, key = '', level = 0, parentArray = false, position = []) =>
Object.entries(obj).reduce((acc, curr, i) => {
const [nodeKey, value] = curr;
const nodeType = typeof value;
const isObject = nodeType === 'object';
const id = parentArray
? `${key}[${nodeKey}]`
: key
? `${key}.${nodeKey}`
: nodeKey;
const pos = [...position, i]
const line = { id, title: nodeKey, type: nodeType, level, pos };
if (!isObject) line.value = value;
acc.push(line);
if (isObject) {
const isArray = Array.isArray(value);
const children = flattenObject(value, id, level + 1, isArray, pos);
acc = [...acc, ...children];
}
return acc;
}, []);
flattenObject(data2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment