Skip to content

Instantly share code, notes, and snippets.

@kraftdorian
Last active March 6, 2021 18:36
Show Gist options
  • Save kraftdorian/dfab0d2daaa5f160e776cd37ce83cc7c to your computer and use it in GitHub Desktop.
Save kraftdorian/dfab0d2daaa5f160e776cd37ce83cc7c to your computer and use it in GitHub Desktop.
Flatten object with paths
const flattenObject = (value, key = null, flattenedObject = {}) => {
if (
['string', 'number', 'bigint', 'boolean', 'undefined', 'symbol'].includes(typeof value) ||
value === null ||
value instanceof Date
) {
flattenedObject[key] = value;
} else if (Array.isArray(value)) {
value.forEach((childValue, childIndex) => {
flattenObject(childValue, `${key}[${childIndex}]`, flattenedObject);
});
} else if (typeof value === 'object') {
let computedKey;
for (const childKey in value) {
computedKey = (typeof key === 'string' ? key + '.' : '') + childKey;
flattenObject(value[childKey], computedKey, flattenedObject);
}
}
return flattenedObject;
};
@kraftdorian
Copy link
Author

kraftdorian commented Mar 6, 2021

Use case:

const data = {
  name: 'name',
  id: Symbol('id'),
  date: new Date(),
  nullable: null,
  notDefined: undefined,
  __meta__: {
    tags: ['tag1', 'tag2', 'tag3'],
    maxSafeInteger: BigInt(Number.MAX_SAFE_INTEGER)
  }
};

flattenObject(data);

Result:

{
  name: 'name',
  id: Symbol(id),
  date: 2021-03-06T18:34:51.813Z,
  nullable: null,
  notDefined: undefined,
  '__meta__.tags[0]': 'tag1',
  '__meta__.tags[1]': 'tag2',
  '__meta__.tags[2]': 'tag3',
  '__meta__.maxSafeInteger': 9007199254740991n
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment