I have an object with some keys, and I want to only keep some of the keys with their value?
I tried with filter
:
A non-lodash way to solve this in a fairly readable and efficient manner:
function filterByKeys(obj, keys = []) {
const filtered = {}
keys.forEach(key => {
if (obj.hasOwnProperty(key)) {
filtered[key] = obj[key]
}
})
return filtered
}
const myObject = {
a: 1,
b: 'bananas',
d: null
}
const result = filterByKeys(myObject, ['a', 'd', 'e']) // {a: 1, d: null}
console.log(result)