对象属性动态删除
我很好奇一种改进的方法来动态删除基于通配符的javascript对象的属性。 首先,假设我有以下对象:
object = { checkbox_description_1 : 'Chatoyant', checkbox_description_2 : 'Desultory', random_property : 'Firefly is a great program', checkbox_mood_1 : 'Efflorescent', checkbox_description_3 : 'Ephemeral' }
任务
现在,最终的结果是以’checkbox_description’为幌子删除了所有属性,并保留对象的其余部分,如下所示:
object = { random_property : 'Firefly is a great program', checkbox_mood_1 : 'Efflorescent', }
我的解决方案
目前我的解决方案涉及jquery和以下代码:
var strKeyToDelete = 'checkbox_description' /* Start looping through the object */ $.each(object, function(strKey, strValue) { /* Check if the key starts with the wildcard key to delete */ if(this.match("^"+strKey) == strKeyToDelete) { /* Kill... */ delete object[strKey]; }; });
问题
关于这一点的东西对我来说似乎非常不优雅,如果对象的尺寸合理,那么过程非常密集。 有没有更好的方法来执行此操作?
这是最低要求:
function deleteFromObject(keyPart, obj){ for (var k in obj){ // Loop through the object if(~k.indexOf(keyPart)){ // If the current key contains the string we're looking for delete obj[k]; // Delete obj[key]; } } } var myObject = { checkbox_description_1 : 'Chatoyant', checkbox_description_2 : 'Desultory', random_property : 'Firefly is a great program', checkbox_mood_1 : 'Efflorescent', checkbox_description_3 : 'Ephemeral' }; deleteFromObject('checkbox_description', myObject); console.log(myObject); // myObject is now: {random_property: "Firefly is a great program", checkbox_mood_1: "Efflorescent"};
所以这非常接近你拥有的jQuery函数。
(虽然速度快一点,考虑到它不使用jQuery,而indexOf
代替match
)
那么, indexOf
之前的~
是什么?
indexOf
返回一个整数值:如果找不到字符串,则返回-1
如果找到, indexOf
返回从0
开始的索引。 (如果找到,总是一个正整数)
~
是按位NOT
,反转此输出。 碰巧的是, indexOf
的反转输出正是我们需要表示“找到”或“未找到”的结果。
~-1
变为0
,为假值。
~x
,其中x
为0
或者为正整数,变为-(x+1)
,即真值。
这样, ~string.indexOf('needle')
就像string.contains('needle')
,这是我们在JavaScript中没有的函数。
另外,您可以在~
前面添加一个双布尔值( !!
),将true-ish或false-ish输出转换为真实的真/假,但这在JavaScript中不是必需的。
在function上, ~string.indexOf('needle')
和!!~string.indexOf('needle')
是相等的。
如果您特别需要钥匙开始针,请更换:
~k.indexOf(keyPart)
附:
k.indexOf(keyPart) === 0
您可以使用如何检查字符串“StartsWith”是否为另一个字符串? :
function deleteFromObject(keyToDelete, obj) { var l = keyToDelete.length; for (var key in obj) if (key.substr(0, l) == keyToDelete) // key begins with the keyToDelete delete obj[key]; }