Extracting properties out of an object natively

懵懂的女人 提交于 2021-02-04 19:12:05

问题


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?


回答1:


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)


来源:https://stackoverflow.com/questions/49890667/extracting-properties-out-of-an-object-natively

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!