可以在单个语句中重建对象并生成新对象吗? [英] Is it possible to destructure an object and generate a new object in a single statement?

查看:165
本文介绍了可以在单个语句中重建对象并生成新对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

const {name, slug, description, parent} = cat;
const saneCat = {name, slug, description, parent};

在第一个表达式中,我们通过解构一个凌乱对象来定义四个常量。在第二个表达式中,我们将它们组合成一个新对象。我想在一个单一的步骤中完成,而不会重复有趣的字段列表,但由于第一个表达式没有定义一个对象,这似乎是不可能的。是不是真的?我们非常接近Clojurian的胜利!

In the first expression, we define four constants by destructuring a messy object. In the second expression, we combine them into a new object. I would like to do this in a single step without duplicating the list of interesting fields, but because the first expression doesn't define an object, this seems to be impossible. Is it really? We are so close to a Clojurian win!

我没有成功尝试过以下内容。任何ECMAScript编译器都是公平的游戏,但是我没有选择使用Clojurescript。

I have tried the following without success. Any ECMAScript compiler is fair game, but I don't have the option of just using Clojurescript.

const saneCat = {name, slug, description, parent} = cat; // name is not defined
const {...saneCat} = {name, slug, description} = cat;  // name is not defined
const saneCat = ({name, slug, description, parent} = cat); // name is not defined
const saneCat = ({name, slug, description, parent}) = cat; // name is not defined
const saneCat = {{name, slug, description, parent}} = cat; // unexpected token
const saneCat = {{name, slug, description, parent}} = {cat}; // unexpected token


推荐答案

不幸的是,ES6中的破坏是有限的分配和参数列表。有一个拣选操作员的讨论,会做你想要的,但不要呼吸。

Unfortunately, destructuring in ES6 is limited to assignments and parameter lists. There is a discussion of a "pick" operator which would do what you want, but don't hold your breath.

同时,你最接近的是以下,它需要复制属性列表:

Meanwhile, the closest you can come is the following, which requires duplicating the list of properties:

const saneCat = 
  (({name, slug, description, parent}) => 
    ({name, slug, description, parent})
  )(cat);

使用提议的选择语法,您可以写

Using the proposed pick syntax, you would be able write

const saneCat = {name, slug, description, parent} # cat;

这样的东西应该出现在ES29中。在此之前,您可以使用评论中提到的类型的选择实用程序,但个人来说,我讨厌将属性写入字符串。

Something like that should show up in ES29. Until then, you can use pick utilities of the sort mentioned in the comment, but personally, I hate writing properties as strings.

另请参见一线从一些物业ES 6中的对象

这篇关于可以在单个语句中重建对象并生成新对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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