Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lodash: find all keys that has particular value in its own array

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

like image 338
jsh6303 Avatar asked Apr 06 '18 13:04

jsh6303


2 Answers

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>
like image 170
Nenad Vracar Avatar answered Sep 22 '22 08:09

Nenad Vracar


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.

like image 38
Kiwi Rupela Avatar answered Sep 24 '22 08:09

Kiwi Rupela