Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter keys of an object with lodash?

People also ask

How do you filter keys in objects?

JavaScript objects don't have a filter() method, you must first turn the object into an array to use array's filter() method. You can use the Object. keys() function to convert the object's keys into an array, and accumulate the filtered keys into a new object using the reduce() function as shown below.

How do you filter with Lodash?

Given an array arr , Lodash's filter() function returns an array containing all the elements in arr for which the function returned a truthy value. The function you pass to filter() is called the predicate. If the predicate returns a falsy value (like null , undefined , 0 , or '' ), Lodash filters that value out.

How do you get the keys of an array of objects?

To convert an array's values to object keys:Declare a new variable and set it to an empty object. Use the forEach() method to iterate over the array. On each iteration, assign the array's element as a key in the object.

How does Lodash filter work?

Lodash helps in working with arrays, collection, strings, objects, numbers etc. The _. filter() method iterates over elements of collection, returning an array of all elements predicate returns true.


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) // 6789
console.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>

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);