user16756868
user16756868

Reputation:

Get similar key from object

I have created below function which checks for key in object & return value but i need the key itself, what fix need to be applied for this ?

function matchKey(objectToSearch, keyToFind) {
    for (var k in objectToSearch) {
        if ( k.toLowerCase().indexOf(keyToFind.toLowerCase()) !== -1) 
            return objectToSearch[k];
    }
    return null;
}

matchKey({year : 2015, "Price/STK" : "value"}, "price"); // returns "value"

desired output = "Price/STK"

Upvotes: 1

Views: 85

Answers (1)

Guerric P
Guerric P

Reputation: 31815

Well just return k instead of objectToSearch[k]:

function matchKey(objectToSearch, keyToFind) {
    for (var k in objectToSearch) {
        if ( k.toLowerCase().indexOf(keyToFind.toLowerCase()) !== -1) 
            return k;
    }
    return null;
}

const result = matchKey({year : 2015, "Price/STK" : "value"}, "price"); // returns "Price/STK"

console.log(result);

Shortest implementation:

const matchKey = (objectToSearch, keyToFind) =>
  Object.keys(objectToSearch).find(
    (k) => k.toLowerCase().indexOf(keyToFind.toLowerCase()) !== -1
  );

const result = matchKey({ year: 2015, "Price/STK": "value" }, "price"); // returns "Price/STK"

console.log(result);

If the object has multiple similar keys and you want the array of matching keys:

const matchKey = (objectToSearch, keyToFind) =>
  Object.keys(objectToSearch).filter(
    (k) => k.toLowerCase().indexOf(keyToFind.toLowerCase()) !== -1
  );

const result = matchKey({ year: 2015, "Price/STK": "value", "sdfsdfpricedsg": "value" }, "price");
// returns "Price/STK"

console.log(result);

Upvotes: 1

Related Questions