Ulysses
Ulysses

Reputation: 6015

javascript: Shortest code to find object key matching a pattern

Consider the object:

var myObj = {
  hugeKey1: 'xxx',
  hugeKey2: 'xxx',
  hugeKey3: 'xxx',
  hugeKey4: 'xxx',
  prettyKey1: 'Only one'
};

Following is the code for getting a list of all keys with pattern hugeKey:

var filteredKeySet = _.filter(
    Object.keys(data),
    function (key) {
        if (key.match(/hugeKey/i)) {
            return true;
        }
    }
);

There is only one key named PrettyKey1, but this the number at the end is dynamic - it could be PrettyKey2 as well.

What's the shortest piece of code to find the first key with pattern match?

Something that looks like Object.keys(myObj).findFirstMatch(/PrettyKey/i);

Upvotes: 2

Views: 748

Answers (4)

Denialos
Denialos

Reputation: 1006

According to your requirements, this is probably what you need:

const firstMatchedKeyNameInObject = Object.keys(myObj).find(keyName => keyName.includes('prettyKey'));

Upvotes: 2

HalfWebDev
HalfWebDev

Reputation: 7648

From

function callback(elm){
    if(elm.match(/prettyKey/i)) return true;
}
Object.keys(myObj).findIndex(callback);

to

Object.keys(myObj).findIndex(key=>key.match(/PrettyKey/i))

or

Object.keys(myObj).findIndex(key=>key.includes('prettyKey'))

Upvotes: 1

j2ko
j2ko

Reputation: 2539

In addition to previous answers, in case you need to perform such operation frequently and the target object is also changing you could write following utility function:

function matchBy(pattern) {
    return obj => Object.keys(obj).find(k => k.match(pattern));
}

or

function findBy(pattern) {
    return obj => Object.keys(obj).find(k => k.includes(pattern));
}

And then use them as :

var match = matchBy(/prettyKey/i);
var find = findBy("prettyKey");

....
console.log(match(myObj));
console.log(find(myObj));

Upvotes: 2

Ulysses
Ulysses

Reputation: 6015

Ok so found a possible answer almost immediately after posting:

Object.keys(myObj).findIndex(x=>x.match(/PrettyKey/i))

Just needed to use the => based index search on the keys.

Wonder if there is a faster way of doing this via lodash.

Upvotes: 0

Related Questions