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.
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.
With pure JavaScript, use: delete thisIsObject['Cow'];
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" }.
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]);
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'); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With