从对象中删除键的最佳方法是什么?

时间:2018-08-06 08:12:26

标签: javascript node.js nsmutablearray

我有一个用例,可以从JSON对象或对象数组中删除多个键。下面是我的代码。如果有人对此有更优化的方法,则建议

       exports.removeAttributes = function (arrayOfAttributesToRemove, object, callback) {
    let checkForRemoveOrRetain = true;
    removeORRetain(arrayOfAttributesToRemove, object, checkForRemoveOrRetain, (err, object) => {
        if (err) {
            callback(err);
        } else {
            callback( object);
        }
    });
};
exports.retainAttributes = function (arrayOfAttributesToRetain, object, callback) {
    let checkForRemoveOrRetain = false;
    removeORRetain(arrayOfAttributesToRemove, object, checkForRemoveOrRetain, (err, object) => {
        if (err) {
            callback(err);
        } else {
            callback(object);
        }
    });
}

    let removeORRetain = function (arrayOfAttributesToRemove, object, checkForRemoveOrRetain, callback) {
    if (Array.isArray(object)) {
        for (let i = 0; i < object.length; i++) {
            for (let key in object[i]) {
                if (arrayOfAttributesToRemove.includes(key) === checkForRemoveOrRetain) {
                    delete object[i][key];
                }
            }
        }
        callback(object);
    } else {
        for (let key in object) {
            if (arrayOfAttributesToRemove.includes(key) === checkForRemoveOrRetain) {
                delete object[key];
            }
        }
        callback( object);
    }
}; 

1 个答案:

答案 0 :(得分:1)

使用lodash可以很容易地做到这一点。


const _ = require('lodash');

exports.removeAttributes = function (arrayOfAttributesToRemove, object, callback) {
   // check for errors etc. Then

   // Create an array of objects if not already.
   const arr = _.concat([], object);
   // call callback with new arr with omitted properties using _.map and _.omit
   callback(null, _.map(arr, e => _.omit(e, arrayOfAttributesToRemove)));
};

如果要保留属性,请使用_.pick