开发者

Removing unwanted keys from my array of objects

My Object

How to remove keys like UserID, UserName from it... i开发者_如何学Python mean selected keys... delete operator is not working in my case.

for (i=0 i <obj.length; i ++) {
    delete obj[i]['keyName']; 
}

The above does not work, neither throws an error. Any other way...


You missed the ; after i=0.

Additionally, obj needs to be MyObject.PatientVitalsGetResult.Vitals


Don't use delete; it will set the element to undefined instead of removing it. Instead, use splice.

var i;
for(i = 0; i < obj.length; i++){
    obj[i].splice('keyName',1);
}


There is no standard way for this, afaik. You will need to perform a conditional copy of the old Object filtering the unwanted properties:

var oldObject = { /* your object */ } ;
var newObject = { } ;

var filter = { "UserID": true , "UserName": true } ;

for(var key in oldObject) 
    if( !(key in filter) ) newObject[key] = oldObject[key] ; 

Then use the acquired newObject in the following code.


var vitals = obj["PatientVitalsGetResult"]["Vitals"];


for (i=0; i < vitals.length; i++) {
    delete(vitals[i]["UserID"])
};


How about this solution....

Array.prototype.containsValue = function (value) {
        for (var k in this) {
            if (!this.hasOwnProperty(k)) {
                continue;
            } //skip inherited properties
            if (this[k] == value) {
                return true;
            }
        }
        return false;
    };

for (var key in Object) {
    var unwantedKeys = ['UserName', 'UserID'];
    if (unwantedKeys.containsValue(key)) continue;
    // Play with your Object it won't contain these unwanted keys.
}

Delete should work, i am not sure about the mistake you are doing..

http://jsfiddle.net/spechackers/43hTD/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜