Skip to content

Instantly share code, notes, and snippets.

@simonespa
Created July 31, 2020 14:26
Show Gist options
  • Select an option

  • Save simonespa/cfa76844a14b5a3ebf7e7901655fb776 to your computer and use it in GitHub Desktop.

Select an option

Save simonespa/cfa76844a14b5a3ebf7e7901655fb776 to your computer and use it in GitHub Desktop.
Dynamically filter object's properties in Javascript
function reducer(object, accumulator, current) {
// check if the object contains a property that matches the current filter
const hasOwnProperty = Object.prototype.hasOwnProperty.call(object, current);
// add it to the accumulator if it has, by dynamically selecting the computed property
return {
...accumulator,
...(hasOwnProperty && { [current]: object[current] })
};
}
function filterProperties(object, filterList) {
// return an empty object if the filterList is not an array
if (!Array.isArray(filterList)) return {};
// otherwise filter the object according to the filterList
return filterList.reduce(reducer.bind(this, object), {});
}
const object = {
aProperty: 'a value',
anotherProperty: 'another value',
prop: {
a: 'a',
b: 'b'
}
};
console.log({['prop']: object['prop']});
// console.log(object['prop']['a']);
// const filter = ['prop'];
// console.log(filterProperties(object, filter));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment