0
var obj={};
var duplicate-flag = false;

if(obj.hasOwnProperty(value))
{
    duplicate-flag = true;
} else {
    flag=false;
}

I am using above code to check list input text elements for duplicates, but fails since its case sensitive.

J Alan
  • 77
  • 1
  • 11
  • Your question title mentions a loop but your example code doesn't have one. I think your example code needs to be fleshed out more so we can see what you're trying to do or how you've attempted it yourself. Also there's no data in your example. – Ryan Tuosto Jul 12 '17 at 17:24
  • duplicate-flag= will fail. Please provide at least useful code. – Jonas Wilms Jul 12 '17 at 17:29
  • Some solutions are here: https://stackoverflow.com/questions/5832888/is-the-hasownproperty-method-in-javascript-case-sensitive – PM 77-1 Jul 12 '17 at 17:32

2 Answers2

1

You actually won't use object.hasOwnProperty() here because that method tests the properties as their names are currently cased. You need the ability to modify the case of the property in question, for the purposes of the test.

For that reason, you can't just check a pre-existing property, you need to loop over the the property names and check them against a supplied value...

Just check a lower-case object property name against a forced lower-case comparison value. Also, you had some syntax errors and unnecessary code. See comments for details.

var obj={
  FOO: 10,
  Special: true
};

function dupCheck(o, val){

  var duplicateFlag = false; // Identifier names can't contain hyphens (-)
  
  for(var prop in o){
    // force property name and value to lower case for comparison
    if(prop.toLowerCase() === val.toLowerCase()){
      duplicateFlag = true;
      break;
    }   // No else branch needed because duplicate starts off false
  }
  
  return duplicateFlag;
}

console.log(dupCheck(obj, "foo"));          // true
console.log(dupCheck(obj, "SPECIAL"));      // true
console.log(dupCheck(obj, "somethingElse"));// false
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
0

Using @Scott Marcus's answer above, modified to prototype

Object.prototype.hasOwnPropertyInsensitive = function (value) {
    for (var prop in this) {
        if (prop.toLowerCase() === value.toLowerCase()) {
            return true;
        }
    }
    return false;
}
Kevin Scheidt
  • 95
  • 3
  • 10