是否可以在现有对象上进行解构?(Javascript ES6)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29620686/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:40:10  来源:igfitidea点击:

Is it possible to destructure onto an existing object? (Javascript ES6)

javascriptecmascript-6destructuring

提问by majorBummer

For example if I have two objects:

例如,如果我有两个对象:

var foo = {
  x: "bar",
  y: "baz"
}

and

var oof = {}

and I wanted to transfer the x and y values from foo to oof. Is there a way to do that using the es6 destructuring syntax?

我想将 x 和 y 值从 foo 转移到 oof。有没有办法使用 es6 解构语法来做到这一点?

perhaps something like:

也许是这样的:

oof{x,y} = foo

采纳答案by loganfsmyth

While ugly and a bit repetitive, you can do

虽然丑陋且有点重复,但你可以做到

({x: oof.x, y: oof.y} = foo);

which will read the two values of the fooobject, and write them to their respective locations on the oofobject.

它将读取foo对象的两个值,并将它们写入对象上的相应位置oof

Personally I'd still rather read

我个人还是更愿意阅读

oof.x = foo.x;
oof.y = foo.y;

or

或者

['x', 'y'].forEach(prop => oof[prop] = foo[prop]);

though.

尽管。

回答by Bergi

No, destructuring does not support member expressions in shorthands but only plain propertynames at the current time. There have been talksabout such on esdiscuss, but no proposals will make it into ES6.

不,解构不支持速记中的成员表达式,但目前仅支持普通的属性名称。目前已经谈关于这样的esdiscuss,但不建议将它做成ES6。

You might be able to use Object.assignhowever - if you don't need all own properties, you still can do

但是,您可能可以使用Object.assign- 如果您不需要所有自己的属性,您仍然可以这样做

var foo = …,
    oof = {};
{
    let {x, y} = foo;
    Object.assign(oof, {x, y})
}

回答by Zfalen

IMO this is the easiest way to accomplish what you're looking for:

IMO 这是完成您正在寻找的最简单方法:

let { prop1, prop2, prop3 } = someObject;
let data = { prop1, prop2, prop3 };

  // data === { prop1: someObject.prop1, ... }

Basically, destructure into variables and then use the initializer shorthand to make a new object. No need for Object.assign

基本上,解构为变量,然后使用初始化器速记来创建一个新对象。不需要Object.assign

I think this is the most readable way, anyways. You can hereby select the exact props out of someObjectthat you want. If you have an existing object you just want to merge the props into, do something like this:

无论如何,我认为这是最易读的方式。您可以在此选择someObject您想要的确切道具。如果您有一个现有的对象,您只想将这些道具合并到其中,请执行以下操作:

let { prop1, prop2, prop3 } = someObject;
let data = Object.assign(otherObject, { prop1, prop2, prop3 });
    // Makes a new copy, or...
Object.assign(otherObject, { prop1, prop2, prop3 });
    // Merges into otherObject

Another, arguably cleaner, way to write it is:

另一种可以说更简洁的写法是:

let { prop1, prop2, prop3 } = someObject;
let newObject = { prop1, prop2, prop3 };

// Merges your selected props into otherObject
Object.assign(otherObject, newObject);

I use this for POSTrequests a lot where I only need a few pieces of discrete data. But, I agree there should be a one liner for doing this.

我经常使用它来处理POST我只需要一些离散数据的请求。但是,我同意这样做应该有一个单衬。

EDIT: P.S. -I recently learned you can use ultra destructuring in the first step to pull nested values out of complex objects! For instance...

编辑:PS -我最近了解到您可以在第一步中使用超解构从复杂对象中提取嵌套值!例如...

let { prop1, 
      prop2: { somethingDeeper }, 
      prop3: { 
         nested1: {
            nested2
         } 
      } = someObject;
let data = { prop1, somethingDeeper, nested2 };

Plus, you could use spread operator instead of Object.assign when making a new object:

另外,您可以在创建新对象时使用扩展运算符而不是 Object.assign:

const { prop1, prop2, prop3 } = someObject;
let finalObject = {...otherObject, prop1, prop2, prop3 };

Or...

或者...

const { prop1, prop2, prop3 } = someObject;
const intermediateObject = { prop1, prop2, prop3 };
const finalObject = {...otherObject, ...intermediateObject };

回答by gafi

Other than Object.assignthere is the object spread syntaxwhich is a Stage 2 proposal for ECMAScript.

除此之外Object.assign还有对象传播语法,它是 ECMAScript 的第 2 阶段提案。

var foo = {
  x: "bar",
  y: "baz"
}

var oof = { z: "z" }

oof =  {...oof, ...foo }

console.log(oof)

/* result 
{
  "x": "bar",
  "y": "baz",
  "z": "z"
}
*/

But to use this feature you need to use stage-2or transform-object-rest-spreadplugin for babel. Here is a demo on babel with stage-2

但是要使用此功能,您需要使用babelstage-2transform-object-rest-spread插件。这是一个关于 babel演示stage-2

回答by Matthias Günter

BabelJS plugin

BabelJS 插件

If you are using BabelJSyou can now activate my plugin babel-plugin-transform-object-from-destructuring(see npm package for installation and usage).

如果您正在使用BabelJS,您现在可以激活我的插件babel-plugin-transform-object-from-destructuring安装和使用请参见 npm 包)。

I had the same issue described in this thread and for me it was very exhausting when you create an object from a destructuring expression, especially when you have to rename, add or remove a property. With this plugin maintaining such scenarios gets much more easier for you.

我在这个线程中遇到了同样的问题,对我来说,当您从解构表达式创建对象时非常累人,尤其是当您必须重命名、添加或删除属性时。使用此插件维护此类场景对您来说变得更加容易。

Object example

对象示例

let myObject = {
  test1: "stringTest1",
  test2: "stringTest2",
  test3: "stringTest3"
};
let { test1, test3 } = myObject,
  myTest = { test1, test3 };

can be written as:

可以写成:

let myTest = { test1, test3 } = myObject;

Array example

数组示例

let myArray = ["stringTest1", "stringTest2", "stringTest3"];
let [ test1, , test3 ] = myArray,
  myTest = [ test1, test3 ];

can be written as:

可以写成:

let myTest = [ test1, , test3 ] = myArray;

回答by Hampus Ahlgren

It's totally possible. Just not in one statement.

这是完全可能的。只是不在一个声明中。

var foo = {
    x: "bar",
    y: "baz"
};
var oof = {};
({x: oof.x, y: oof.y} = foo); // {x: "bar", y: "baz"}

(Do note the parenthesis around the statement.) But keep in mind legibility is more important than code-golfing :).

(请注意语句周围的括号。)但请记住,易读性比打代码更重要:)。

Source: http://exploringjs.com/es6/ch_destructuring.html#sec_assignment-targets

来源:http: //exploringjs.com/es6/ch_destructuring.html#sec_assignment-targets

回答by CampSafari

You can just use restructuring for that like this:

您可以像这样使用重组:

const foo = {x:"a", y:"b"};
const {...oof} = foo; // {x:"a", y:"b"} 

Or merge both objects if oof has values:

或者如果 oof 有值则合并两个对象:

const foo = {x:"a", y:"b"};
let oof = {z:"c"}
oof = Object.assign({}, oof, foo)

回答by Ben Copeland

You can return the destructured object in an arrow function, and use Object.assign() to assign it to a variable.

您可以在箭头函数中返回解构后的对象,并使用 Object.assign() 将其分配给一个变量。

const foo = {
  x: "bar",
  y: "baz"
}

const oof = Object.assign({}, () => ({ x, y } = foo));

回答by user5733033

DRY

干燥

var a = {a1:1, a2: 2, a3: 3};
var b = {b1:1, b2: 2, b3: 3};

const newVar = (() => ({a1, a2, b1, b2})).bind({...a, ...b});
const val = newVar();
console.log({...val});
// print: Object { a1: 1, a2: 2, b1: 1, b2: 2 }

or

或者

console.log({...(() => ({a1, a2, b1, b2})).bind({...a, ...b})()});

回答by RPichioli

You can destruct an object assigning directly to another object attribute.

您可以销毁直接分配给另一个对象属性的对象。

Working example:

工作示例:

let user = {};
[user.name, user.username] = "Stack Overflow".split(' ');
document.write(`
1st attr: ${user.name} <br /> 
2nd attr: ${user.username}`);

You can work with destructing using variables with the same name of object attribute you want to catch, this way you don't need to do:

您可以使用与要捕获的对象属性名称相同的变量进行破坏,这样您就不需要执行以下操作:

let user = { name: 'Mike' }
let { name: name } = user;

Use this way:

使用这种方式:

let user = { name: 'Mike' }
let { name } = user;

The same way you can set new values to object structures if they have the same attribute name.

如果对象结构具有相同的属性名称,则可以通过相同的方式为它们设置新值。

Look this working example:

看看这个工作示例:

// The object to be destructed
let options = {
  title: "Menu",
  width: 100,
  height: 200
};

// Destructing
let {width: w, height: h, title} = options;

// Feedback
document.write(title + "<br />");  // Menu
document.write(w + "<br />");      // 100
document.write(h);                 // 200