user1107173
user1107173

Reputation: 10754

Extracting properties out of an object natively

I use underscore.js library to extract properties out of an object. Is there a more native JS way to accomplish the same:

var fullObject = {'name': 'Jack', 'age': 39, 'device': 'tablet', 'team': 'Red'}
const {name, device, team} = fullObject
console.log(name, device, team) // Jack tablet Red

Is there a way to create a new object through destructuring?

I would like to assign the values of name, device, team to a new object.

Currently I do:

const {name, device, team} = fullObject
const newObject = {name, device, team}
console.log(newObject) // { name: 'jack', device: 'tablet', team: 'red' }

Is there a better way to do this?

Upvotes: 3

Views: 76

Answers (1)

Patrick Roberts
Patrick Roberts

Reputation: 51886

If you extract a particular sub-object in several places and you want it to be more DRY, you can write a curried function that accepts the keys to pick, and then returns another function that accepts an object to extract them from.

See below for usage:

const pick = (...keys) => (obj) => keys.reduce((acc, k) => (acc[k] = obj[k], acc), {})
const nameDeviceTeam = pick('name', 'device', 'team')

const fullObject = { name: 'Jack', age: 39, device: 'tablet', team: 'red' }
const newObject = nameDeviceTeam(fullObject)

console.log(newObject)

Upvotes: 2

Related Questions