在JavaScript中从对象复制某些属性的最有效方法是什么? [英] What is the most efficient way to copy some properties from an object in JavaScript?

查看:117
本文介绍了在JavaScript中从对象复制某些属性的最有效方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说,我有一个对象:

const user = {_id: 1234, firstName: 'John', lastName: 'Smith'}

我想创建另一个没有 _id的对象 key:

I want to create another object without the _id key:

const newUser = {firstName: 'John', lastName: 'Smith'}

我使用的是:

const newUser = Object.assign({}, {firstName: user.firstName, lastName: user.lastName})

有更好的方法吗?

推荐答案

你可以通过解构和对象实现它rest属性:

You can achieve it with destructuring and object rest properties:

const user = {_id: 1234, fistName: 'John', lastName: 'Smith'}
const {_id, ...rest} = user;
console.log(rest);

然而 rest / rpread属性仍然是 ecmascript的提案(目前在阶段3)。你可以将它用于像babel这样的转换层。

However rest/rpread properties are still an ecmascript's proposal (currently at stage 3). You can use it with transpilation layer such as babel.

这篇关于在JavaScript中从对象复制某些属性的最有效方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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