如何使用lodash过滤对象的键? [英] How to filter keys of an object with lodash?
本文介绍了如何使用lodash过滤对象的键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个带有一些键的对象,我只想保留一些带有它们的值的键?
I have an object with some keys, and I want to only keep some of the keys with their value?
我尝试使用 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>
但它打印了一个数组:
[111, 222]
这不是我想要的.
如何用 lodash 做到这一点?如果 lodash 不起作用,或者其他什么?
How to do it with lodash? Or something else if lodash is not working?
推荐答案
Lodash 有一个 _.pickBy
函数,它完全符合您的要求.
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>
这篇关于如何使用lodash过滤对象的键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文