Skip to content

Instantly share code, notes, and snippets.

@talesluna-zz
Created August 23, 2020 16:25
Show Gist options
  • Save talesluna-zz/90637592594b3b52bae9f50aa17c68b9 to your computer and use it in GitHub Desktop.
Save talesluna-zz/90637592594b3b52bae9f50aa17c68b9 to your computer and use it in GitHub Desktop.
Covert complex javascript object into a one level object with dotted keys
interface DotObjectOptions {
ignoreArrays?: boolean
}
export const dotObject = (object: Record<string, unknown>, options: DotObjectOptions = {}) => {
if (!object || typeof object !== 'object') {
throw Error('Not a object');
}
const { ignoreArrays } = options;
const dottedObject = {};
Object
.keys(object)
.forEach(key => {
const value = object[key];
if (!value || typeof value !== 'object' || (ignoreArrays && Array.isArray(value))) {
dottedObject[key] = value;
return;
}
const subObject = dotObject(value as Record<string, unknown>);
Object
.keys(subObject)
.forEach(subKey => {
dottedObject[`${key}.${subKey}`] = subObject[subKey];
});
});
return dottedObject;
};
const dottedObject = dotObject({
    name: 'homer',
    age: 39,
    address: {
        country: 'united states',
        city: 'springfield',
    },
    parents: [
        { id: 5, name: 'lisa' },
        { id: 8, name: 'meggie' }
    ],
    pets: ['santa claus little helper', 'snowball']
});

/* Output
{
    'name': 'homer',
    'age': 39,
    'address.country': 'united states',
    'address.city': 'springfield',
    'parents.0.id': 5,
    'parents.0.name': 'lisa',
    'parents.1.id': 8,
    'parents.1.name': 'meggie',
    'pets.0': 'santa claus little helper',
    'pets.1': 'snowball'',
}*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment