Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slice specific keys in javascript object

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?

like image 454
starwars25 Avatar asked Jan 07 '16 15:01

starwars25


People also ask

Can you use slice on an object JavaScript?

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.

Can you use slice on an object?

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.

How do I remove a key from a JavaScript object?

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.


2 Answers

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);
like image 161
kuboon Avatar answered Nov 12 '22 13:11

kuboon


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')
)
like image 21
Oleksandr T. Avatar answered Nov 12 '22 11:11

Oleksandr T.