Freewind Freewind - 2 years ago 583
Javascript Question

How to filter keys of an object with lodash?

I have an object with some keys, and I want to only keep some of the keys with their value?

I tried with


var data = {

var result = _.filter(data, function(value, key) {
return key.startsWith("a");


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?

Live demo:,output

Answer Source

Lodash has a _.pick function which does exactly what you're looking for.

var thing = {
  "a": 123,
  "b": 456,
  "abc": 6789

var result = _.pick(thing, function(value, key) {
  return _.startsWith(key, "a");

console.log( // 6789
console.log(result.b)   // undefined
<script src=""></script>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download