开发者

Deleting the keys in an array of object and checking its length

var uniqueProperties = [];    
for (var i = 0, length = obj.length; i < length; i++) {
        for (var prop in obj[i]) {
            if (prop == null || prop == ' ') {
                delete obj[i][prop];
            }
        }
        for (var prop in obj[i]) {
            if (this.uniqueProperties.indexOf(prop) === -1) {
                t开发者_如何学Chis.uniqueProperties.push(prop);
            }
        }

    }

I want to first delete the keys with null or blank values, and then add them in the array and check its length.

I think its not getting deleted.


In the first loop, you're checking to see if "prop" is null or (incorrectly) the empty string, but that doesn't really make sense. You should be checking the value of that property of "obj[i]":

    if (obj[i][prop] == null || obj[i][prop] == '')
      delete obj[i][prop];

Also, your "uniqeProperties" list should also be "assisted" by a separate object so that you can avoid the poor algorithmic performance of repeated linear scans:

    var uniqueProperties = [], uniqueMap = {};

    // ...

    for (var prop in obj[i]) {
        if (!this.uniqueMap[prop]) {
            this.uniqueMap[prop] = true;
            uniqueProperties.push(prop);
        }
    }


Why do you want to delete the keys....

for (var key in object) {

    if (!object.hasOwnProperty(key)) {
        continue;
    } //to skip inherited properties
    if (!key[object]) {
        continue;
    } //skip null or blank values
}

delete obj[i][propertyName] is a bad coding practice. You shouldn't delete properties directly in your incoming data since the results can sometimes be unpredictable and cause lots of headaches in the debugging stage.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜