Skip to content

Instantly share code, notes, and snippets.

@domzgarcia
Last active November 9, 2018 07:30
Show Gist options
  • Save domzgarcia/128ae89565c5835c2c85f68358011fa0 to your computer and use it in GitHub Desktop.
Save domzgarcia/128ae89565c5835c2c85f68358011fa0 to your computer and use it in GitHub Desktop.
Filter, Object, keys, Allow, Include, exclude function and undefined
// Google Search
// Tags
// Filter, Object, keys, Allow, Include
// list of allowed properties
let allowed = ['prop', 'account', 'eVar']
// kindly see reponse json above
function filterByAllowedKeys(allowed, data){
let responseKeys = Object.keys(data)
// check if function
const isFunction = (name) => {
return name && {}.toString.call(name) === '[object Function]';
};
// if key is part of keys pool
const isKeyFrom = (allowed, curKey) => {
let isValid = false
for(var i=0; i< allowed.length; i++){
let RE = new RegExp(allowed[i])
isValid = RE.test(curKey)
if(isValid) return true
}
return isValid
}
let collection =
responseKeys.reduce( (list, key, idx) => {
let temp = {};
/**
* should part of allowed key
* should not be a function
* should not undefined
* */
if( isKeyFrom(allowed, key) === true &&
isFunction(data[key]) === false &&
data[key] !== undefined ){
temp = {...temp, [key]: data[key] }
}
return {...list, ...temp}
}, {})
return collection;
}
let result = filterByAllowedKeys(allowed, response)
console.log(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment