我有一个我想要过滤的对象。这就是我使用的:
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)
}
});
});
我该如何处理?
答案 0 :(得分:3)
您是否尝试删除所有没有以" teststring开头的键的键值对 - "?如果是的话......
for(var key in query){
if(query.hasOwnProperty(key) && key.indexOf('teststring-') === -1){
delete query[key];
}
}
答案 1 :(得分:2)
使用delete
运算符:
$.each(query, function(key, value) {
if(key.indexOf('teststring-') == -1) {
delete query[key];
}
});
http://jsfiddle.net/NvZyA/(在此演示中,Object.keys()
用于显示所有密钥)。
答案 2 :(得分:1)
您可能正在寻找delete
运营商。
答案 3 :(得分: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];
}
});
答案 4 :(得分:0)
正如其他人所说,使用delete
运算符。但是不需要迭代对象的属性:
var query = {
"teststring-123" : true,
"teststring-12344566" : false,
test: true
};
delete query['test'];
答案 5 :(得分: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);