从对象本地提取属性 [英] Extracting properties out of an object natively

查看:41
本文介绍了从对象本地提取属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 underscore.js 库从对象中提取属性.是否有更本地的JS方法来实现相同目的:

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?

我想将 name device team 的值分配给新对象.

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

我目前正在这样做:

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

有更好的方法吗?

推荐答案

如果您在多个位置提取了特定的子对象,并且希望它更干燥,则可以编写一个咖喱函数来接受要选择的键,然后返回另一个函数,该函数接受一个对象以从中提取它们.

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.

用法见下文:

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)

这篇关于从对象本地提取属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆