2012-05-04 91 views
0

我有一個對象,我想過濾。這是我用:按鍵名過濾對象

query = { 
    "teststring-123": "true", 
    "teststring-12344566": "false", 
    test: "true" 
} 

我想,這樣過濾後,我只需要篩選查詢:

query = { 
    "teststring-123": "true", 
    "teststring-12344566": "false" 
} 

$(query).each(function(index, value) { 
    $.each(value, function(i, v) { 
     if(i.indexOf('teststring-')==-1) { 
      // remove part of query object where index is this one  
      console.log(index) 
     } 
    });  
}); 

我如何處理呢?

回答

1

您可能正在尋找delete運營商。

3

您是否試圖刪除所有沒有以「teststring-」開頭的鍵的鍵值對?如果是這樣的......

for(var key in query){ 
    if(query.hasOwnProperty(key) && key.indexOf('teststring-') === -1){ 
     delete query[key]; 
    } 
} 
+1

像這樣,純粹的javascript! –

1

使用delete操作:

var query = { 
    "teststring-123": "true", 
    "teststring-12344566": "false", 
    test: "true" 
} 
$.each(query, function(sKey) { 
    if (sKey.indexOf("teststring-") < 0) { // or check if it is not on first position: != 0 
     delete query[sKey]; 
    } 
}); 
0

正如其他人所說,使用delete操作。然而,不需要重複該對象的屬性:

var query = { 
    "teststring-123" : true, 
    "teststring-12344566" : false, 
    test: true 
}; 

delete query['test']; 
+0

鑰匙事先未知。 OP想要刪除不以''teststring *'開始的鍵 –

+0

是的,Rob W是正確的..我不知道哪些其他鍵存在並且需要過濾所有不以「teststring」開頭的.. –

0

喜歡這個?

var query = { 
    "teststring-123": "true", 
    "teststring-12344566": "false", 
    "test": "true" 
} 
var newobj = {}; 

$.each(query, function(i, v) { 
    if(i.indexOf('teststring-') != -1) { 
     // remove part of query object where index is this one   
     console.log(i); 
     newarr[i] = v; 
    } 
}); 
console.log(newobj); 
+0

非常好,如果用戶可能使用嚴​​格模式,並且它包含在全局插件或其他內容中。 – noob