I am using lodash to perform the following task to the array below:
let map = {
"John": ["math", "physics", "chem"],
"Lisa": ["bio", "chem", "history"],
"Emily": ["math", "history", "javascript"];
}
Using lodash, how can I return the key that has value "javascript" in its array, in this case Emily
?
I was using
_.keys(_.pickBy(map, e => {
return (e == 'javascript');
}))
but this does not seem to work
You could use findKey
and includes
methods to find the key.
let map = {
"John": ["math", "physics", "chem"],
"Lisa": ["bio", "chem", "history"],
"Emily": ["math", "history", "javascript"]
}
const result = _.findKey(map, e => _.includes(e, 'javascript'))
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.js"></script>
To match multiple keys where value contains the element you could use pickBy
method to filter properties and then get keys.
let map = {
"John": ["math", "physics", "chem"],
"Lisa": ["bio", "chem", "history", "javascript"],
"Emily": ["math", "history", "javascript"]
}
const result = _.keys(_.pickBy(map, e => _.includes(e, "javascript")))
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.js"></script>
For getting all keys in array format we use below code
let map1 = {
"John": ["math", "physics", "chem"],
"Lisa": ["bio", "chem", "history","javascript"],
"Emily": ["math", "history", "javascript"];
}
_.compact(_.map(map1,(v,k)=>{if(v.indexOf("javascript")>-1) return k; }))
This works for me fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With