3

I wanted to find the key in object with case insensitive.

Object is very large, so I can not modify the object to make all the keys in lowercase/uppercase.

For example.

I have var _columns = {...} Now I need to find whether Id key exists in it or not. Currently i am using if else to solve this problem.

if (this._columns['Id']) {
    this._idColumnName = 'Id';
} else if (this._columns['id']) {
    this._idColumnName = 'id';
} else if (this._columns['ID']) {
    this._idColumnName = 'ID';
}

S is there any way to check the presence of key by using any pattern or any other way in JavaScript.

Morteza Asadi
  • 1,819
  • 2
  • 22
  • 39
Pavan Tiwari
  • 3,077
  • 3
  • 31
  • 71

2 Answers2

8

Using Array.prototype.find():

function containsKey(object, key) {
  return !!Object.keys(object).find(k => k.toLowerCase() === key.toLowerCase());
}

// example
let o = {
  Id: "001"  
};

console.log(containsKey(o, 'ID')); // prints true
console.log(containsKey(o, 'id')); // prints true
console.log(containsKey(o, 'Id')); // prints true

If you want to return the property name instead of a boolean, remove the !! from the returned value.

function findKey(object, key) {
    return Object.keys(object).find(k => k.toLowerCase() === key.toLowerCase());
}
Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156
  • This is a good solution. The question wording is a bit unclear, but from the OP's code perhaps they want to return the property name rather than a boolean - if so, obviously that'd just be a minor tweak to your code. – nnnnnn Feb 22 '17 at 06:20
  • @nnnnnn Thanks. Updated my answer. – Robby Cornelissen Feb 22 '17 at 06:25
0

Since Array.prototype.find() and Array.prototype.findIndex() still have some limited support (mainly on mobile browsers), I had to come up with a cross-browser solution, so I originally wrote this to check for the existence of the findIndex() function:

function findObjKey(find, obj) {
    var keys = Object.keys(obj);

  if (typeof keys.findIndex === 'function') {    
    var f = keys.findIndex(function(e) {
        if (this.toLowerCase() === e.toLowerCase()) { return true; }
    }, find);

    if (~f) { return keys[f]; }
  } else {
    for (var i = 0; i < keys.length; i++) {
      if (find.toLowerCase() === keys[i].toLowerCase()) { return keys[i]; }
    }
  }

  return false;
}

However, I discovered that looping through each of the keys is actually faster than using findIndex()!

findIndex(): 0.258056640625ms

Object.keys loop: 0.19384765625ms

So, I came up with this which should work for any browsers that support Object.keys and also works with either Objects or Arrays:

function findKey(find, obj) {
  if (obj.constructor === Object) { obj = Object.keys(obj); }
  for (var i = 0; i < obj.length; i++) {
    if (find.toLowerCase() === obj[i].toLowerCase()) { return obj[i]; }
  }
  return false;
}
Kodie Grantham
  • 1,963
  • 2
  • 17
  • 27