Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering object by keys in lodash

I wrote the function below to return all keys in an object that match a specific pattern. It seems really round-about because there's no filter function in lodash for objects, when you use it all keys are lost. Is this the only way to filter an objects keys using lodash?

export function keysThatMatch (pattern) {
  return (data) => {
    let x = _.chain(data)
    .mapValues((value, key) => {
      return [{
        key: key,
        value: value
      }]
    })
    .values()
    .filter(data => {
      return data[0].key.match(pattern)
    })
    .zipWith(data => {
      let tmp = {}
      tmp[data[0].key] = data[0].value
      return tmp
    })
    .value()
    return _.extend.apply(null, x)
  }
}
like image 598
ThomasReggi Avatar asked Feb 12 '16 19:02

ThomasReggi


People also ask

How do you filter objects with keys?

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.

What is pickBy Lodash?

Lodash helps in working with arrays, strings, objects, numbers, etc. The _. pickBy() method is used to return a copy of the object that composed of the object properties predicate returns truthy for. Syntax: _.pickBy( object, predicate )


2 Answers

You can use pickBy from lodash to do this. (https://lodash.com/docs#pickBy)

This example returns an object with keys that start with 'a'

var object = { 'a': 1, 'b': '2', 'c': 3, 'aa': 5};

o2 = _.pickBy(object, function(v, k) {
    return k[0] === 'a';
});

o2 === {"a":1,"aa":5}
like image 136
bwbrowning Avatar answered Nov 07 '22 01:11

bwbrowning


I don't think you need lodash for this, I would just use Object.keys, filter for matches then reduce back down to an object like this (untested, but should work):

export function keysThatMatch (pattern) {
  return (data) => {
    return Object.keys(data).filter((key) => {
      return key.match(pattern);
    }).reduce((obj, curKey) => {
      obj[curKey] = data[curKey];
      return obj;
    });
  }
}
like image 30
Rob M. Avatar answered Nov 06 '22 23:11

Rob M.