下划线:从对象数组中删除所有键/值对

时间:2021-05-13 07:36:41

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:

我可以用下面的JS来解决这个问题,但我对我的解决方案并不满意:

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

Any suggestions much appreciated.

感谢任何建议。

2 个解决方案

#1


49  

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

#2


0  

For Omit

的省略

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

For Pick

为选择

_.map(arr, _.partial(_.pick, _, 'q'));

#1


49  

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

#2


0  

For Omit

的省略

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

For Pick

为选择

_.map(arr, _.partial(_.pick, _, 'q'));