使用下划线(技术上为Lodash)。有一个类似于以下内容的对象。

var myObj = {
    first: {name: 'John', occupation: 'Welder', age: 30},
    second: {name: 'Tim', occupation: 'A/C Repair', kids: true},
    third: {name: 'Dave', occupation: 'Electrician', age: 32},
    fourth: {name: 'Matt', occupation: 'Plumber', age: 41, kids: false}
};


我还想从每个对象中“清理”一个数组的哈希:

var excludes = {
    first: ['name', 'age'],
    second: ['occupation'],
    fourth: ['kids]
};


这个想法是将数组中的每个元素从具有匹配键的对象中删除。这意味着我的数据将最终如下所示:

{
    first: {occupation: 'Welder'},
    second: {name: 'Tim', kids: true},
    third: {name: 'Dave', occupation: 'Electrician', age: 32},
    fourth: {name: 'Matt', occupation: 'Plumber', age: 41}
};


我本来是在尝试:

_.map(myObj, function(obj, k) {
    if(_.has(excludes, k) {
        // not sure what here
    }
});


我本来想在最内层使用省略,但是一次只能删除一个键,而不能列出一个键。

最佳答案

实际上,_.omit可以列出一个键列表:

result = _.transform(myObj, function(result, val, key) {
    result[key] = _.omit(val, excludes[key]);
});

09-17 23:28