Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Underscore: remove all key/value pairs from an array of object

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.

like image 644
Iladarsda Avatar asked Apr 07 '14 16:04

Iladarsda


People also ask

How do I remove a key from an array of objects?

To remove a property from all objects in an array:Use the Array. forEach() method to iterate over the array. On each iteration, use the delete operator to delete the specific property. The property will get removed from all objects in the array.

How to remove key value pair from object in JavaScript?

With pure JavaScript, use: delete thisIsObject['Cow'];

How do you delete a key pair in an object?

The delete operator is used to delete the key-value pair where the key is “key2”. console. log(obj); The output of the above code in the console will be: { key1: "value1", key3: "value3" }.

How do you remove a key value pair from an object in typescript?

When only a single key is to be removed we can directly use the delete operator specifying the key in an object. Syntax: delete(object_name. key_name); /* or */ delete(object_name[key_name]);


1 Answers

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'); }); 
like image 57
p.s.w.g Avatar answered Sep 24 '22 02:09

p.s.w.g