在lodash中按键过滤对象 [英] Filtering object by keys in lodash

查看:111
本文介绍了在lodash中按键过滤对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了下面的函数来返回与特定模式匹配的对象中的所有键。它看起来真的很圆,因为在lodash对象中没有过滤器功能,当你使用它时,所有的键都会丢失。这是使用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)
  }
}


推荐答案

我认为你不需要lodash,我只想用 Object.keys ,过滤匹配然后减少回到这样的对象(未经测试,但应该工作):

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

这篇关于在lodash中按键过滤对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆