我很好奇有一种改进的方法可以根据通配符从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];
};
});问题
对我来说,这似乎是非常不优雅的,如果对象的大小是合理的,那么过程就会非常密集。有没有更好的方法来执行这个操作?
发布于 2012-12-14 16:55:33
这是最低要求:
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;如果找到,则返回从0开始的索引。(因此,如果找到,始终为正整数)
~是一个逐位NOT,用于反转此输出。碰巧的是,indexOf的反转输出正好是我们需要指示的“找到”或“未找到”。
~-1变成了0,一个类似于false的值。
当x为0或正值时,~x将变为-(x+1),这是一个接近真的值。
这样,~string.indexOf('needle')的行为就像string.contains('needle'),这是我们在JavaScript中没有的功能。
此外,您可以在~前面添加一个双布尔值not (!!),以将true-ish或false-ish输出转换为真正的true / false,但在JavaScript中不需要这样做。
在功能上,~string.indexOf('needle')和!!~string.indexOf('needle')是相等的。
如果您特别需要用针开始的密钥,请替换:
~k.indexOf(keyPart)通过以下方式:
k.indexOf(keyPart) === 0https://stackoverflow.com/questions/13875338
复制相似问题