javascript - Filter object by keyname - Stack Overflow

admin2025-04-16  0

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?

Share edited Aug 22, 2015 at 9:10 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked May 4, 2012 at 16:13 ho.sho.s 7513 gold badges18 silver badges43 bronze badges
Add a ment  | 

6 Answers 6

Reset to default 3

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);
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1744810284a268235.html

最新回复(0)