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'',
}*/
Created
August 23, 2020 16:25
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
}; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment