Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove certain elements from map in Javascript

how can i remove all the key/value pairs from following map, where key starts with X.

var map = new Object(); 
map[XKey1] = "Value1";
map[XKey2] = "Value2";
map[YKey3] = "Value3";
map[YKey4] = "Value4";

EDIT

Is there any way through regular expression, probably using ^ . Something like map[^XKe], where key starts with 'Xke' instead of 'X'

like image 290
newbie Avatar asked Sep 03 '13 18:09

newbie


People also ask

How do you delete an object on a map?

delete() The delete() method removes the specified element from a Map object by key.

How do I remove a value from a map?

HashMap remove() Method in Java HashMap. remove() is an inbuilt method of HashMap class and is used to remove the mapping of any particular key from the map. It basically removes the values for any particular key in the Map.

How can you remove all elements inside of a map object?

map. clear(obj); map. obj() takes an object as a parameter and removes each and every value so as to make it empty.

How do you remove an element from an array in JavaScript?

Array elements can be deleted using the JavaScript operator delete . Using delete leaves undefined holes in the array. Use pop() or shift() instead.


2 Answers

You can iterate over map keys using Object.key.

The most simple solution is this :

DEMO HERE

Object.keys(map).forEach(function (key) {
 if(key.match('^'+letter)) delete obj[key];
});

So here is an other version of removeKeyStartsWith with regular expression as you said:

function removeKeyStartsWith(obj, letter) {
  Object.keys(obj).forEach(function (key) {
     //if(key[0]==letter) delete obj[key];////without regex
           if(key.match('^'+letter)) delete obj[key];//with regex

  });
}

var map = new Object(); 
map['XKey1'] = "Value1";
map['XKey2'] = "Value2";
map['YKey3'] = "Value3";
map['YKey4'] = "Value4";

console.log(map);
removeKeyStartsWith(map, 'X');
console.log(map);

Solution with Regex will cover your need even if you use letter=Xke as you said but for the other solution without Regex , you will need to replace :

Key[0]==letter with key.substr(0,3)==letter

like image 165
Charaf JRA Avatar answered Oct 04 '22 16:10

Charaf JRA


I'd suggest:

function removeKeyStartsWith(obj, letter) {
    for (var prop in obj) {
        if (obj.hasOwnProperty(prop) && prop[0] == letter){
            delete obj[prop];
        }
    }
}

JS Fiddle demo.

Incidentally, it's usually easier (and seems to be considered 'better practice') to use an Object-literal, rather than a constructor, so the following is worth showing (even if, for some reason, you prefer the new Object() syntax:

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 to allow for the user to search for a property that starts with a given string, ends with a given string or (by using both startsWith and endsWith) is 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.

References:

  • Object.hasOwnProperty().
  • JavaScript Regular Expressions.
like image 35
David Thomas Avatar answered Oct 04 '22 15:10

David Thomas