Freewind Freewind - 5 months ago 188
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

filter
:

var data = {
"aaa":111,
"abb":222,
"bbb":333
};

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

console.log(result);


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: http://jsbin.com/moqufevigo/1/edit?js,output

Answer

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(result.abc) // 6789
console.log(result.b)   // undefined
<script src="https://cdn.rawgit.com/lodash/lodash/3.0.1/lodash.min.js"></script>