Skip to content

Instantly share code, notes, and snippets.

@VitorLuizC
Last active January 20, 2018 14:55
Show Gist options
  • Select an option

  • Save VitorLuizC/95df5bde3137a9b7094697362ae717e3 to your computer and use it in GitHub Desktop.

Select an option

Save VitorLuizC/95df5bde3137a9b7094697362ae717e3 to your computer and use it in GitHub Desktop.
{
  profile: {
    soma: 20,
    menor: 1
  }
}

After getProperties

{
  'profile.soma': 20,
  'profile.menor': 1
}
const isObject = (value) => value && typeof value === 'object';
const isFilled = (value) => typeof value === 'string' && value.trim();
const reduceObject = (object, fn) => {
const entries = Object.entries(object);
const reduction = entries.reduce(
(object, entry) => Object.assign({}, object,fn(...entry)),
{}
);
return reduction;
};
const getProperties = (value, parent) => {
const isValid = isObject(value) || isFilled(parent);
if (!isValid) {
throw new Error('Can\'t concat non-object values without parent.');
return;
}
if (!isFilled(parent)) {
return reduceObject(value, (property, value) => getProperties(value, property));
}
if (!isObject(value)) {
return {
[parent]: value
};
}
return reduceObject(value, (property, value) => getProperties(value, `${parent}.${property}`));
};
export default getProperties;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment