I would suggest:
function removeKeyStartsWith(obj, letter) { for (var prop in obj) { if (obj.hasOwnProperty(prop) && prop[0] == letter){ delete obj[prop]; } } }
JS Fiddle demo .
By the way, it is usually simpler (and, apparently, considered "best practice") to use a literal object rather than a constructor, so you should show the following (even if for some reason you prefer new Object()
:
var map = { 'XKey1' : "Value1", 'XKey2' : "Value2", 'YKey3' : "Value3", 'YKey4' : "Value4", };
JS Fiddle demo .
If you really want to use regular expressions (but why?), Then the following works:
function removeKeyStartsWith(obj, letter, caseSensitive) { // case-sensitive matching: 'X' will not be equivalent to 'x', // case-insensitive matching: 'X' will be considered equivalent to 'x' var sensitive = caseSensitive === false ? 'i' : '', // creating a new Regular Expression object, // ^ indicates that the string must *start with* the following character: reg = new RegExp('^' + letter, sensitive); for (var prop in obj) { if (obj.hasOwnProperty(prop) && reg.test(prop)) { delete obj[prop]; } } } var map = new Object(); map['XKey1'] = "Value1"; map['XKey2'] = "Value2"; map['YKey3'] = "Value3"; map['YKey4'] = "Value4"; console.log(map); removeKeyStartsWith(map, 'x', true); console.log(map);
JS Fiddle demo .
Finally (at least for now) an approach that extends the Object
prototype, allowing the user to search for a property that begins with a given string, ends with a given string or (using both startsWith
and endsWith
) - a given string (with or without case sensitivity:
Object.prototype.removeIf = function (needle, opts) { var self = this, settings = { 'beginsWith' : true, 'endsWith' : false, 'sensitive' : true }; opts = opts || {}; for (var p in settings) { if (settings.hasOwnProperty(p)) { settings[p] = typeof opts[p] == 'undefined' ? settings[p] : opts[p]; } } var modifiers = settings.sensitive === true ? '' : 'i', regString = (settings.beginsWith === true ? '^' : '') + needle + (settings.endsWith === true ? '$' : ''), reg = new RegExp(regString, modifiers); for (var prop in self) { if (self.hasOwnProperty(prop) && reg.test(prop)){ delete self[prop]; } } return self; }; var map = { 'XKey1' : "Value1", 'XKey2' : "Value2", 'YKey3' : "Value3", 'YKey4' : "Value4", }; console.log(map); map.removeIf('xkey2', { 'beginsWith' : true, 'endsWith' : true, 'sensitive' : false }); console.log(map);
JS Fiddle demo .
Literature: