Created
July 31, 2020 14:26
-
-
Save simonespa/cfa76844a14b5a3ebf7e7901655fb776 to your computer and use it in GitHub Desktop.
Dynamically filter object's properties in Javascript
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
| 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