本文介绍了如何用lodash过滤对象的键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个键的对象,我只想保留一些键的值?
我试着用过滤器:
var data = {
aaa:111,
abb:222,
bbb:333
};
var result = _.filter(data,function(value,key){
return key.startsWith(a);
})
console.log(result);
但它打印一个数组:
这不是我想要的。
如何用lodash做到这一点?或者别的东西,如果lodash不工作?
现场演示:
解决方案
Lodash有功能
$ b
var thing = { a:123,b:456,abc:6789}; var result = _.pickBy(thing,function(value,key){return _.startsWith(key,a);}); console.log(result.abc)// 6789console.log(result.b)// undefined
< script src =https://cdn.jsdelivr.net/lodash/4.16.4/lodash.min.js>< / script>
I have an object with some keys, and I want to only keep some of the keys with their value?
I tried with filter:
var data = { "aaa":111, "abb":222, "bbb":333 }; var result = _.filter(data, function(value, key) { return key.startsWith("a"); }) console.log(result);
But it prints an array:
[111, 222]
Which is not what I want.
How to do it with lodash? Or something else if lodash is not working?
Live demo: http://jsbin.com/moqufevigo/1/edit?js,output
解决方案
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过滤对象的键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!