Home > Blockchain >  lodash _.findKey equivalent in Javascript or jQuery
lodash _.findKey equivalent in Javascript or jQuery

Time:01-13

I have a series of pieces in a game and at the beginning I store their store DIV complete with styling in an object with the respective key being an encrypted number. At the end of the game I check the piece that has been clicked on to see if its current z-index matches that of the original styling stored in the object. Currently I am using lodash which works perfectly but I would like to remove lodash so as not to have to load this extra libary. My problem is, I simply can't translate the three lines of code into pure Javascript (or jQuery for that matter) - I'm quite a beginner and have now spent hours trying to resolve this. Any advice would be appreciated. Here my "lodash" code:

var myVar = _.findKey(myObject, function (storedDIV) {
    return storedDIV.css('z-index') == clickedDIV.css('z-index');
});

CodePudding user response:

You can create a similar function to _.findKey() using Object.keys and Array.find(). The function accepts a predicate, or you can use the default identity predicate (o => o), but it doesn't support the other lodash _.findKey() shorthands.

const findKey = (obj, predicate = o => o) => Object.keys(obj)
    .find(key => predicate(obj[key], key, obj))

// example 1 - passing a predicate
const users = {'barney':  { 'age': 36, 'active': true },'fred':    { 'age': 40, 'active': false },'pebbles': { 'age': 1,  'active': true }}
console.log(findKey(users, o => o.age < 40)) // barney

// example 2 - using default identity predicate
const flags = { a: false, b: true, c: false }
console.log(findKey(flags)) // b

  •  Tags:  
  • Related