Skip to content

Instantly share code, notes, and snippets.

@tylerpaige
Created April 13, 2017 19:40
Show Gist options
  • Save tylerpaige/04798d596b3980d5519921e794396e51 to your computer and use it in GitHub Desktop.
Save tylerpaige/04798d596b3980d5519921e794396e51 to your computer and use it in GitHub Desktop.
Take an array of objects, and standardize a specific property's value.
/*
Standardize data set so that variations of a value can be lumped together with the same property value.
This function will overwrite properties... Maybe it would be better for it to add a new field.
@param data {object} an array of objects that will be sorted
@param key {string} the object property to test in every record in the data array
@param rules {object} an object of arrays defining which values can be combined
@param combineRest {boolean} whether or not to combined records that do not match any rules
⤷ if true, all records that do not match a rule will have their property `key` set to `"other"`
⤷ if false, all records that do not match a rule will maintain their existing property `key`
# example
var data = [
{color : 'orange', type : 'orange'},
{color : 'green', type : 'watermelon'},
{color : 'green', type : 'lime'},
{color : 'red', type : 'strawberry'}
];
combineByKey(data, 'type', {
'citrus' : ['orange', 'tangerine', 'lime'],
'melon' : ['watermelon', 'cantaloupe']
}, true);
>[
{color : 'orange', type : 'citrus'},
{color : 'green', type: 'melon'},
{color : 'green', type : 'citrus'},
{color : 'red', type : 'other'}
]
*/
const standardizeByKey = (data, key, rules, combineRest) => {
return data.map((d) => {
//The current value for the given key
const val = d[key];
//The matching value that will replace the current value
//Will return undefined if no match
const group = Object.keys(rules).find(r => rules[r].includes(val));
//New object to merge with existing record.
const update = {};
//Group values by rules, group non-matches into category "other"
update[key] = group || (combineRest ? 'other' : val);
//Return the merged object
return Object.assign({}, d, update)
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment