In rails, i have a special slice
method to keep in Hash
only keys I need. It is very handy to permit only required keys in a hash.
Is there a method like this in Node.js?
The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end ( end not included) where start and end represent the index of items in that array. The original array will not be modified.
The slice() method returns a copy of an array's portion into a new array object. This object is selected from start to end . As a note, the original array will not be modified. Also, if a new element is added to one of the arrays, the other array will not be affected.
Use delete to Remove Object Keys The special JavaScript keyword delete is used to remove object keys (also called object properties). While you might think setting an object key equal to undefined would delete it, since undefined is the value that object keys that have not yet been set have, the key would still exist.
These are the coolest solutions.
Hard corded version: https://stackoverflow.com/a/39333479/683157
const object = { a: 5, b: 6, c: 7 };
const picked = (({ a, c }) => ({ a, c }))(object);
console.log(picked); // { a: 5, c: 7 }
Generic version: https://stackoverflow.com/a/32184094/683157
const pick = (...props) => o => props.reduce((a, e) => ({ ...a, [e]: o[e] }), {});
pick('color', 'height')(elmo);
In JavaScript there is no such method, however, in libraries like lodash
there is the method called _.pick
var data = { a: 1, b: 2, c: 3 };
console.log(_.pick(data, 'a', 'c'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.js"></script>
you can install lodash
via npm
npm install lodash --save
and then require it to your project
var _ = require('lodash') // import all methods
// or just import pick method
// var pick = require('lodash/object/pick');
Or you can implement your own pick with new ES features, like so
const data = { a: 1, b: 2, c: 3 };
const pick = (obj, ...args) => ({
...args.reduce((res, key) => ({ ...res, [key]: obj[key] }), { })
})
console.log(
pick(data, 'a', 'b')
)
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