jQuery 在Javascript中从地图中删除某些元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18599242/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove certain elements from map in Javascript
提问by newbie
how can i remove all the key/value pairs from following map, where key starts with X.
如何从以下地图中删除所有键/值对,其中键以 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'
有没有办法通过正则表达式,可能使用 ^ 。类似于 map[^XKe],其中键以 'Xke' 而不是 'X' 开头
采纳答案by Charaf JRA
You can iterate over map keys using Object.key
.
您可以使用 迭代映射键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:
所以这是removeKeyStartsWith
你所说的正则表达式的另一个版本:
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 :
Regex
即使您像您所说的那样使用 letter=Xke ,解决方案 with也能满足您的需求,但对于没有 Regex 的其他解决方案,您需要替换:
Key[0]==letter
with key.substr(0,3)==letter
Key[0]==letter
和 key.substr(0,3)==letter
回答by David says reinstate Monica
I'd suggest:
我建议:
function removeKeyStartsWith(obj, letter) {
for (var prop in obj) {
if (obj.hasOwnProperty(prop) && prop[0] == letter){
delete obj[prop];
}
}
}
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:
顺便说一句,使用对象字面量而不是构造函数通常更容易(并且似乎被认为是“更好的做法”),因此以下内容值得展示(即使出于某种原因,您更喜欢new Object()
语法:
var map = {
'XKey1' : "Value1",
'XKey2' : "Value2",
'YKey3' : "Value3",
'YKey4' : "Value4",
};
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);
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
andendsWith
) isa given string (with, or without, case-sensitivity:
最后(至少现在)一种扩展Object
原型的方法,允许用户搜索以给定字符串开头、以给定字符串结尾或(通过同时使用startsWith
和endsWith
)是给定字符串(带有,或没有,区分大小写:
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);
References:
参考:
回答by Manindar
You can get it in this way easily.
您可以通过这种方式轻松获得它。
var map = new Object();
map['Key1'] = "Value1";
map['Key2'] = "Value2";
map['Key3'] = "Value3";
map['Key4'] = "Value4";
console.log(map);
delete map["Key1"];
console.log(map);
This is easy way to remove it.
这是删除它的简单方法。
回答by haylem
Preconditions
先决条件
Assuming your original input:
假设您的原始输入:
var map = new Object();
map[XKey1] = "Value1";
map[XKey2] = "Value2";
map[YKey3] = "Value3";
map[YKey4] = "Value4";
And Assuming a variable pattern
that would contain what you want to keys to be filtered against (e.g. "X"
, "Y"
, "prefixSomething"
, ...).
并假设变量pattern
,将包含您想进行对抗被过滤密钥(例如"X"
,"Y"
,"prefixSomething"
,...)。
Solution 1 - Using jQuery to Filter and Create a New Object
解决方案 1 - 使用 jQuery 过滤和创建新对象
var clone = {};
$.each(map, function (k, v) {
if (k.indexOf(pattern) == 0) { // k not starting with pattern
clone[k] = v;
}
});
Solution 2 - Using Pure ECMAScript and Creating a New Object
解决方案 2 - 使用纯 ECMAScript 并创建新对象
var clone = {};
for (var k in map) {
if (map.hasOwnProperty(k) && (k.indexOf(pattern) == 0)) {
clone[k] = map[k];
}
}
Solution 3 - Using Pure ECMAScript and Using the Source Object
解决方案 3 - 使用纯 ECMAScript 和使用源对象
for (var k in map) {
if (map.hasOwnProperty(k) && (k.indexOf(pattern) == 0)) {
delete map[k];
}
}
Or, in modern browsers:
或者,在现代浏览器中:
Object.keys(map).forEach(function (k) {
if (k.indexOf(pattern) == 0) {
delete map[k];
}
});
Update - Using Regular Expressions for the Pattern Match
更新 - 使用正则表达式进行模式匹配
Instead of using the following to match if the key k
starts with a letter with:
如果键k
以字母开头,则不要使用以下内容进行匹配:
k[0] == letter // to match or letter
or to match if the key k
starts with a string with:
或匹配键是否k
以字符串开头:
k.indexOf(pattern) // to match a string
you can use instead this regular expression:
你可以改用这个正则表达式:
new Regexp('^' + pattern).test(k)
// or if the pattern isn't variable, for instance you want
// to match 'X', directly use:
// /^X/.test(k)