简体   繁体   English

用下划线省略键数组

[英]Omit array of keys with Underscore

Using Underscore (technically Lodash). 使用下划线(技术上为Lodash)。 Have an object that looks like the following. 有一个类似于以下内容的对象。

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}
};

I also have a hash of arrays that I want to "clean" out of each object: 我还想从每个对象中“清理”一个数组的哈希:

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

The idea is that each of the elements in the array will be dropped from the object that has the matching key. 这个想法是将数组中的每个元素从具有匹配键的对象中删除。 Meaning my data will end up like this: 这意味着我的数据将最终如下所示:

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

I was originally trying: 我本来是在尝试:

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

I was thinking of using omit at the innermost level, but I can only drop one key at a time, not a list of keys. 我当时想在最内层使用省略,但是一次只能删除一个键,而不能一次列出键。

Actually, _.omit can take a list of keys: 实际上, _.omit可以列出一个键列表:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM