I have an object with some keys, and I want to only keep some of the keys with their value?
I tried with filter
:
const data = {_x000D_
aaa: 111,_x000D_
abb: 222,_x000D_
bbb: 333_x000D_
};_x000D_
_x000D_
const result = _.filter(data, (value, key) => key.startsWith("a"));_x000D_
_x000D_
console.log(result);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
_x000D_
But it prints an array:
[111, 222]
Which is not what I want.
How to do it with lodash? Or something else if lodash is not working?
This question is related to
javascript
filter
lodash
Just change filter to omitBy
const data = { aaa: 111, abb: 222, bbb: 333 };_x000D_
const result = _.omitBy(data, (value, key) => !key.startsWith("a"));_x000D_
console.log(result);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
_x000D_
Here is an example using lodash
4.x:
const data = {_x000D_
aaa: 111,_x000D_
abb: 222,_x000D_
bbb: 333_x000D_
};_x000D_
_x000D_
const result = _.pickBy(data, (value, key) => key.startsWith("a"));_x000D_
_x000D_
console.log(result);_x000D_
// Object { aaa: 111, abb: 222 }
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>_x000D_
<strong>Open your javascript console to see the output.</strong>
_x000D_
Native ES2019 one-liner
const data = {
aaa: 111,
abb: 222,
bbb: 333
};
const filteredByKey = Object.fromEntries(Object.entries(data).filter(([key, value]) => key.startsWith("a")))
console.log(filteredByKey);
_x000D_
A non-lodash way to solve this in a fairly readable and efficient manner:
function filterByKeys(obj, keys = []) {_x000D_
const filtered = {}_x000D_
keys.forEach(key => {_x000D_
if (obj.hasOwnProperty(key)) {_x000D_
filtered[key] = obj[key]_x000D_
}_x000D_
})_x000D_
return filtered_x000D_
}_x000D_
_x000D_
const myObject = {_x000D_
a: 1,_x000D_
b: 'bananas',_x000D_
d: null_x000D_
}_x000D_
_x000D_
const result = filterByKeys(myObject, ['a', 'd', 'e']) // {a: 1, d: null}_x000D_
console.log(result)
_x000D_
Source: Stackoverflow.com