Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
51
rated 0 times [  58] [ 7]  / answers: 1 / hits: 79279  / 11 Years ago, tue, september 3, 2013, 12:00:00

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'


More From » jquery

 Answers
2

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


[#75922] Monday, September 2, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
emilee

Total Points: 365
Total Questions: 113
Total Answers: 109

Location: Monaco
Member since Fri, Sep 24, 2021
3 Years ago
emilee questions
;