Underscore: remove all key/value pairs from an arr

2019-02-04 01:40发布

Is there a "smart" underscore way of removing all key/value pairs from an array of object?

e.g. I have following array:

var arr = [
        { q: "Lorem ipsum dolor sit.", c: false },
        { q: "Provident perferendis veniam similique!", c: false },
        { q: "Assumenda, commodi blanditiis deserunt?", c: true },
        { q: "Iusto, dolores ea iste.", c: false },
    ];

and I want to get the following:

var newArr = [
        { q: "Lorem ipsum dolor sit." },
        { q: "Provident perferendis veniam similique!" },
        { q: "Assumenda, commodi blanditiis deserunt?" },
        { q: "Iusto, dolores ea iste." },
    ];

I can get this working with the JS below, but not really happy with my solutions:

for (var i = 0; i < arr.length; i++) {
    delete arr[i].c;
};

Any suggestions much appreciated.

2条回答
干净又极端
2楼-- · 2019-02-04 01:59

For Omit

_.map(arr, _.partial(_.omit, _, 'c'));

For Pick

_.map(arr, _.partial(_.pick, _, 'q'));
查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-02-04 02:07

You can use map and omit in conjunction to exclude specific properties, like this:

var newArr = _.map(arr, function(o) { return _.omit(o, 'c'); });

Or map and pick to only include specific properties, like this:

var newArr = _.map(arr, function(o) { return _.pick(o, 'q'); });
查看更多
登录 后发表回答