Is it possible to use LoDash _.filter
to return values if you only know a key contains a certain string? So let's say you have the following data:
Mydata{
"banana" : "1"
}
And I want to return the values that contain "ana"? Everything I found on LoDash is mostly about searching the element values but not the keys.
If you want to get an array of the values, which keys conform to a criterion, Lodash's _.filter()
works with objects as well. The 2nd param passed to the callback is the key.
var data = { "banana": 1, 'lorem': 2, '123ana': 3 } var result = _.filter(data, function(v, k) { return _.includes(k, 'ana'); }); console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
If you want an object, which properties conform to a certain criterion, you can use _.pickBy()
in a similar way.
var data = { "banana": 1, 'lorem': 2, '123ana': 3 } var result = _.pickBy(data, function(v, k) { return _.includes(k, 'ana'); }); console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
You could reach desired result using native Array#reduce
and return an object containing only these keys, which includes given string
.
const obj = { banana: 'foo', hello: 'bar', foo: 'fzz', ana: 'xoo', } const check = (obj, str) => { return Object.keys(obj).reduce((s, a) => { if (a.includes(str)) { s[a] = obj[a]; } return s; }, {}); } console.log(check(obj, 'ana'));
You can first use filter()
to get keys with specific part of string and then map()
to get values.
var data = { "banana": 1, 'lorem': 2, '123ana': 3 } var result = _.chain(data) .keys() .filter(e => _.includes(e, 'ana')) .map(e => data[e]) .value() console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.