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.
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.
Share Improve this question asked Jul 28, 2017 at 15:59 WJMWJM 1,2011 gold badge16 silver badges30 bronze badges3 Answers
Reset to default 7If 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./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./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./ajax/libs/lodash.js/4.17.4/lodash.js"></script>