Javascript 如何使用lodash过滤对象的键?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30726830/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:39:34  来源:igfitidea点击:

How to filter keys of an object with lodash?

javascriptfilterlodash

提问by Freewind

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

我有一个带有一些键的对象,我只想保留其中一些键的值?

I tried with filter:

我试过filter

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

const result = _.filter(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>

But it prints an array:

但它打印了一个数组:

[111, 222]

[111, 222]

Which is not what I want.

这不是我想要的。

How to do it with lodash? Or something else if lodash is not working?

如何用 lodash 做到这一点?如果 lodash 不起作用,或者其他什么?

回答by serg10

Lodash has a _.pickByfunctionwhich does exactly what you're looking for.

Lodash 有一个_.pickBy函数,它完全符合你的要求。

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>

回答by Krystian Jankowski

Just change filter to omitBy

只需将过滤器更改为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>

回答by PaulMest

Here is an example using lodash4.x:

下面是一个使用lodash4.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>

回答by thomax

A non-lodash way to solve this in a fairly readable and efficient manner:

一种以相当可读和有效的方式解决这个问题的非 lodash 方法:

function filterByKeys(obj, keys = []) {
  const filtered = {}
  keys.forEach(key => {
    if (obj.hasOwnProperty(key)) {
      filtered[key] = obj[key]
    }
  })
  return filtered
}

const myObject = {
  a: 1,
  b: 'bananas',
  d: null
}

const result = filterByKeys(myObject, ['a', 'd', 'e']) // {a: 1, d: null}
console.log(result)