How to filter keys of an object with lodash?
Lodash has a _.pickBy
function which does exactly what you're looking for.
var thing = { "a": 123, "b": 456, "abc": 6789};var result = _.pickBy(thing, function(value, key) { return _.startsWith(key, "a");});console.log(result.abc) // 6789console.log(result.b) // undefined
<script src="https://cdn.jsdelivr.net/lodash/4.16.4/lodash.min.js"></script>
Just change filter to omitBy
const data = { aaa: 111, abb: 222, bbb: 333 };const result = _.omitBy(data, (value, key) => !key.startsWith("a"));console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
Here is an example using lodash
4.x:
const data = { aaa: 111, abb: 222, bbb: 333};const result = _.pickBy(data, (value, key) => key.startsWith("a"));console.log(result);// Object { aaa: 111, abb: 222 }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script><strong>Open your javascript console to see the output.</strong>