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)
        }
    });     
});

我该如何处理?

4

6 回答 6

3

您是否要删除所有没有以“teststring-”开头的键的键值对?如果是这样...

for(var key in query){
    if(query.hasOwnProperty(key) && key.indexOf('teststring-') === -1){
        delete query[key];
    }
}
于 2012-05-04T16:18:34.167 回答
2

使用delete运算符:

$.each(query, function(key, value) {
    if(key.indexOf('teststring-') == -1) {
        delete query[key];
    }
});     

http://jsfiddle.net/NvZyA/(在这个演示中,Object.keys()用于显示所有键)。

于 2012-05-04T16:17:09.493 回答
1

您可能正在寻找delete运营商。

于 2012-05-04T16:17:47.707 回答
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];
    }  
});
于 2012-05-04T16:19:06.707 回答
0

正如其他人所说,使用delete运算符。但是,无需迭代对象的属性:

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

delete query['test'];
于 2012-05-04T16:22:21.017 回答
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);
于 2012-05-04T16:26:12.733 回答