I have an object which I want to filter. This is what I use:
query = {
"teststring-123": "true",
"teststring-12344566": "false",
test: "true"
}
I want to filter query so that after filtering I just have:
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)
}
});
});
How can I handle this?
I have an object which I want to filter. This is what I use:
query = {
"teststring-123": "true",
"teststring-12344566": "false",
test: "true"
}
I want to filter query so that after filtering I just have:
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)
}
});
});
How can I handle this?
Are you trying to remove all key-value pairs that don't have keys starting with "teststring-"? If so...
for(var key in query){
if(query.hasOwnProperty(key) && key.indexOf('teststring-') === -1){
delete query[key];
}
}
Use the delete
operator:
$.each(query, function(key, value) {
if(key.indexOf('teststring-') == -1) {
delete query[key];
}
});
http://jsfiddle/NvZyA/ (in this demo, Object.keys()
is used to show all keys).
You are probably looking for the delete
operator.
Use the delete
operator:
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];
}
});
As the others have said, use the delete
operator. There is no need to iterate the object's properties however:
var query = {
"teststring-123" : true,
"teststring-12344566" : false,
test: true
};
delete query['test'];
Like this?
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);